package com.softgraf.control;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;

import com.softgraf.model.dao.ClienteDAO;
import com.softgraf.model.dao.FabricaDeConexoes;
import com.softgraf.model.dao.FarmaciaProperties;
import com.softgraf.model.dao.TabelasFarmaciaDAO;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

public class Principal extends Application {

	protected static FabricaDeConexoes fabricaConexoes;
	protected static Connection conexao;
	protected static ClienteDAO clienteDAO;
	protected static Stage palco;
	
	
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		
		if (!inicializarBancoDados())
			Platform.exit();
		
		palco = stage;
		
		URL arquivoFXML = this.getClass().getResource("/com/softgraf/view/PainelPrincipal.fxml");
		Parent painel = (Parent) FXMLLoader.load(arquivoFXML);
		
		stage.setScene(new Scene(painel, 900, 650));
		stage.setTitle(Sistema.TITULO);
		stage.setOnCloseRequest(e -> fechar(e));	
		stage.show();
	}
	
	private boolean inicializarBancoDados(){
		String arqConfig = "d:/farmacia.properties";
		FarmaciaProperties farmaciaProperties;
		TabelasFarmaciaDAO tabelas;
		
		try {
			farmaciaProperties = new FarmaciaProperties(arqConfig);
			fabricaConexoes = new FabricaDeConexoes(farmaciaProperties);
			conexao = fabricaConexoes.criarConexao();
			
			if (conexao != null){
				tabelas = new TabelasFarmaciaDAO(conexao);
				if (tabelas.criarTabelaCliente())
					clienteDAO = new ClienteDAO(conexao);
				else
					return false;
			} else
				return false;
			
		} catch (IOException e) {
			Sistema.dlgErro.setHeaderText("Falha de inicialização com o banco de dados");
			Sistema.dlgErro.setContentText(e.getMessage());
			Sistema.dlgErro.showAndWait();
			return false;
		}
		
		return true;
	}
	
	
	private void fechar(WindowEvent e){
		Sistema.dlgInfo.setHeaderText("Atenção!");
		Sistema.dlgInfo.setContentText("Use o menu Sistema -> Sair para fechar");
		Sistema.dlgInfo.showAndWait();
		e.consume();
	}

}
