package Controllers;

import Controllers.Traitement.MyWindow;
import Controllers.Traitement.ParametreSystem;
import Models.SimpleDataAchat;
import Models.SimpleDataVente;
import Models.User.Profile;
import Models.User.ProfileDB;
import Models.User.User;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;


public class AuthentificationController implements Initializable{
    
    @FXML
    private Label label;
    
    @FXML
    private TextField Login;
    
    
    @FXML
    private AnchorPane Content;
    
    @FXML
    private ImageView ImageViewLogo;
    
    @FXML 
    private ProgressBar ProgressBarAuthentification;
    
    private Service<Void> ThreadAuthentification;
    
    Profile profile;
    
    int nbrBonEnter ;
    int nbrDevisClt ;
    int nbrCommandeClt ;
    int nbrBonLivraisonClt ;
    int nbrFactureClt ;
    int nbrBonReception ;
    int nbrFactureFrs ;
    
    Logger logger = Logger.getLogger(AuthentificationController.class.getName());
    
    @Override
    public void initialize(URL url, ResourceBundle rb) 
    {
        Content.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    Connexion();
                }
            }
        });
        setImageLogo();
    }
    
    
    @FXML
    private void handleButtonAction(ActionEvent event) throws IOException {
        this.Connexion();
    }
    
    private void Connexion()
    {
        Login.setStyle("-fx-border-color: transparent;");
        Login.setStyle("-fx-border-color: transparent;");
            
        String login= Login.getText();
        
        Login.setStyle("-fx-border-color: transparent;");
        
        ProgressBarAuthentification.setVisible(true);
        ThreadAuthentification = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        ParametreSystem parametre = new ParametreSystem();
                        
                        boolean resultJsonParametre =  parametre.SetJsonParametre("http://powerpme.com/demo/parametre?login="+login);
                        
                        if(resultJsonParametre == false)
                        {
                            profile = new ProfileDB().getProfileByConnexion("3", "3");
                            User.idprofile= profile.getIdprofile();
                            User.nom = profile.getNom();
                            User.prenom=profile.getPrenom();
                            User.UserLocal=profile.getAuthentification().getLocalNom();
                            User.SotckNegatif= profile.getAuthentification().isStockNegatif();
                            parametre.SetParametre();
                        }
                        
                        setNbrSimpleData();
                        SimpleDataVente simpleDataVente = new SimpleDataVente();
                        simpleDataVente.setDataBonEnter(nbrBonEnter);
                        simpleDataVente.setDataDevisClt(nbrDevisClt);
                        simpleDataVente.setDataCommandeClt(nbrCommandeClt);
                        simpleDataVente.setDataBonLivraisonClt(nbrBonLivraisonClt);
                        simpleDataVente.setDataFactureClt(nbrFactureClt);
                        
                        SimpleDataAchat simpleDataAchat = new SimpleDataAchat();
                        simpleDataAchat.setDataBonReception(nbrBonReception);
                        simpleDataAchat.setDataFactureFrs(nbrFactureFrs); 
                        
                        return null;
                    }
                };
            }
        };
        ThreadAuthentification.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event)
            {
                //Fermer la fenétre de authentification
                //((Node)(event.getSource())).getScene().getWindow().hide();
                Content.getScene().getWindow().hide();
                MyWindow.NewMyStage();
                try {
                    MyWindow.setMyParent((Parent) FXMLLoader.load(getClass().getResource("/Views/Principal.fxml")));
                    Scene scene = new Scene(MyWindow.myParent);
                    MyWindow.myStage.setScene(scene);
                    MyWindow.myStage.show();
                } catch (IOException ex) {
                    logger.error("AuthentificationController  : Principal.fxml :" + ex.getMessage());
                }
                ProgressBarAuthentification.setVisible(false);
            }
        });
        ThreadAuthentification.start();
        
    }

    
    private void setImageLogo()
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // optional, but recommended
            // process XML securely, avoid attacks like XML External Entities (XXE)
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

            // parse XML file
            DocumentBuilder db = dbf.newDocumentBuilder();

            //PowerERP\conf\logo.xml
            Document doc = db.parse(new File("./conf/logo.xml"));

            doc.getDocumentElement().normalize();

            Element elementCNX  = (Element) doc.getElementsByTagName("Connexion").item(0);
            
            String pathLogo = elementCNX.getElementsByTagName("PathImage").item(0).getTextContent();
            FileInputStream fis = new FileInputStream(pathLogo);
            ImageViewLogo.setImage(new Image(fis));
            
            ImageViewLogo.setFitWidth(Double.parseDouble(elementCNX.getElementsByTagName("FitWidth").item(0).getTextContent()));
            ImageViewLogo.setFitHeight(Double.parseDouble(elementCNX.getElementsByTagName("FitHeight").item(0).getTextContent()));
            ImageViewLogo.setLayoutX(Double.parseDouble(elementCNX.getElementsByTagName("LayoutX").item(0).getTextContent()));
            ImageViewLogo.setLayoutY(Double.parseDouble(elementCNX.getElementsByTagName("LayoutY").item(0).getTextContent()));
        } 
        catch (ParserConfigurationException | SAXException | IOException e) {
            System.out.println("error AuthentificationController/setImageLogo "+e.getMessage());
        }
    }
    
    
    private void setNbrSimpleData()
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // optional, but recommended
            // process XML securely, avoid attacks like XML External Entities (XXE)
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

            // parse XML file
            DocumentBuilder db = dbf.newDocumentBuilder();

            //PowerERP\conf\parametre.xml
            Document doc = db.parse(new File("./conf/parametre.xml"));

            doc.getDocumentElement().normalize();

            Element elementSimpleData  = (Element) doc.getElementsByTagName("SimpleData").item(0);

            String strBonEnter = elementSimpleData.getElementsByTagName("BonEnter").item(0).getTextContent();
            nbrBonEnter = Integer.parseInt(strBonEnter);
            
            String strDevisClt = elementSimpleData.getElementsByTagName("DevisClt").item(0).getTextContent();
            nbrDevisClt = Integer.parseInt(strDevisClt);
             
            String strCommandeClt = elementSimpleData.getElementsByTagName("CommandeClt").item(0).getTextContent();
            nbrCommandeClt = Integer.parseInt(strCommandeClt);
             
            String strBonLivraisonClt = elementSimpleData.getElementsByTagName("BonLivraisonClt").item(0).getTextContent();
            nbrBonLivraisonClt = Integer.parseInt(strBonLivraisonClt);
             
            String strFactureClt = elementSimpleData.getElementsByTagName("FactureClt").item(0).getTextContent();
            nbrFactureClt = Integer.parseInt(strFactureClt);
             
            String strBonReception = elementSimpleData.getElementsByTagName("BonReception").item(0).getTextContent();
            nbrBonReception = Integer.parseInt(strBonReception);
             
            String strFactureFrs = elementSimpleData.getElementsByTagName("FactureFrs").item(0).getTextContent();
            nbrFactureFrs = Integer.parseInt(strFactureFrs);
        } 
        catch (ParserConfigurationException | SAXException | IOException e) {
            System.out.println("error AuthentificationController/setNbrSimpleData "+e.getMessage());
        }
    }
    
    private String fetchJsonData(String urlString) throws Exception 
    {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();

        return content.toString();
    }
}
