package Controllers;

import Controllers.Traitement.MyWindow;
import Controllers.Traitement.ParametreSystem;
import Models.User.Profile;
import Models.User.ProfileDB;
import Models.User.User;
import com.gluonhq.charm.glisten.control.ProgressBar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.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.PasswordField;
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 javafx.scene.text.Text;
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 Text Erreurresult;
    
    @FXML
    private Label label;
    
    @FXML
    private TextField Login;
    
    @FXML
    private PasswordField Password;
    
    @FXML
    private AnchorPane Content;
    
    @FXML
    private ImageView ImageViewLogo;
    
    @FXML 
    private ProgressBar ProgressBarAuthentification;
    
    private Service<Void> ThreadAuthentification;
    
    Profile profile;
    
    @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()
    {
        Erreurresult.setText(null);
        Login.setStyle("-fx-border-color: transparent;");
        Login.setStyle("-fx-border-color: transparent;");
            
        String login=Login.getText();
        String password=Password.getText();
            
        if(login.length()==0){
            Erreurresult.setText(null);
            Erreurresult.setText("champ login vide.");
            Login.setStyle("-fx-border-color:#ff0000;");
        }
        else if(password.length()==0){
            Erreurresult.setText(null);
            Erreurresult.setText("champ password vide.");
            Password.setStyle("-fx-border-color:#ff0000;");
        }
        else{
            Login.setStyle("-fx-border-color: transparent;");
            Password.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{

                            profile = new ProfileDB().getProfileByConnexion(login, password);  

                            return null;
                        }
                    };
                }
            };
            ThreadAuthentification.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
                @Override
                public void handle(WorkerStateEvent event){
                    if(profile.getIdprofile() > 0){
                        User.idprofile= profile.getIdprofile();
                        User.nom = profile.getNom();
                        User.prenom=profile.getPrenom();
                        User.UserLocal=profile.getAuthentification().getLocalNom();
                        User.SotckNegatif= profile.getAuthentification().isStockNegatif();

                        if(ParametreSystem.NomLocalPC.equals(profile.getAuthentification().getLocalNom())){
                            //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.getLogger(AuthentificationController.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }else{
                            //Fermer la fenétre de authentification else{
                            Erreurresult.setText("Accès interdit a ce locale");
                        }
                    }else{
                        Erreurresult.setText("Login ou password est incorrect");
                    }
                    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());
        }
    }
    
}
