/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers.User;

import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.contro;
import Models.User.Authentification;
import Models.User.Profile;
import Models.User.ProfileDB;
import Models.User.User;
import Models.connexion;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.animation.FadeTransition;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.util.Duration;

/**
 * FXML Controller class
 * @author Maher Ben Tili
 */
public class ProfileController implements Initializable {

    /**
     * Initializes the controller class.
     */
    @FXML public Text Monprofilenomprenom ;
    @FXML public Text Monprofilenaissance ;
    @FXML public Text ModifierCompteTitre ;
    @FXML public Text Monprofiletele ;
    @FXML public Text Monprofileadresse ;
    @FXML public Text Monprofilesexe ;
    @FXML public Text Monprofilemail ;
    @FXML public Text Monprofilepays ;
    @FXML public Text Monprofiletypecompte ;
    @FXML public Text Monprofilequestion ;
    @FXML public Text Monprofilereponse ;
    
    @FXML public AnchorPane AnchorPaneModierProduit ;
    @FXML public TextField Modiferprofileprenom ;
    @FXML public TextField Modiferprofilenom;
    @FXML public TextField Modiferprofiletele;
    @FXML public TextField Modiferprofileadresse;
    @FXML public TextField Modiferprofilemail;
    @FXML public TextField Modiferprofilepay;
    @FXML public DatePicker Modiferprofilenaissance;
    @FXML public RadioButton Modiferprofilehomme ;
    @FXML public RadioButton Modiferprofilefemme ;
    @FXML public ToggleGroup groupesexe;
    @FXML public GridPane Modiferprofilegridpane;
    @FXML public Text erreurprenom ;
    @FXML public Text erreurnom ;
    @FXML public Text erreurtele ;
    @FXML public Text erreuradresse ;
    @FXML public Text erreurmail ;
    @FXML public Text erreurpay ;
    @FXML public Text erreurnaissance ;
    
    
    
    @FXML public AnchorPane AnchorPaneModiferPass ;
    @FXML public PasswordField ModiferPassAncien ;
    @FXML public PasswordField ModiferPassNouveau ;
    @FXML public PasswordField ModiferPassRepeter ;
    @FXML public TextField ModiferPassReponce ;
    @FXML public ComboBox ModiferPassQuestion ;
    @FXML public GridPane ModiferPassgridpane;
    @FXML public Text erreurAncien ;
    @FXML public Text erreurNouveau ;
    @FXML public Text erreurRepeter ;
    @FXML public Text erreurReponce ;
    @FXML public Text erreurQuestion ;
    
    @FXML private Button ButtonSavePofile;
    @FXML private Button ButtonSavePassword;
    
    connexion cnx = new connexion();
    ShowDialog SD =new ShowDialog();
    
    Profile myprofile= new Profile();
    
    ProfileDB profiledb = new ProfileDB();
    Date date = new Date();
    SimpleDateFormat  dateformat = new SimpleDateFormat ("dd/MM/yyyy");
    contro clt = new contro();
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        //myprofile.setIdprofile(User.idprofile);
        Modiferprofilehomme.setUserData("1");
        Modiferprofilefemme.setUserData("0");
        
        myprofile = profiledb.getpro(User.idprofile);
       
        
        if (myprofile!= null){
            Monprofilenomprenom.setText(myprofile.getNom()+" "+myprofile.getPrenom());
            Monprofilenaissance.setText(Adaptateur.NormalDateFormat(myprofile.getNaissance()));
            Monprofiletele.setText(Integer.toString(myprofile.getTele()));
            Monprofileadresse.setText(myprofile.getAdresse());
            Monprofilesexe.setText(myprofile.getSexeString());
            Monprofilemail.setText(myprofile.getMail());
            Monprofilepays.setText(myprofile.getPays());
            Monprofiletypecompte.setText(myprofile.getAuthentification().getTypeCompte()) ;
            Monprofilequestion.setText(myprofile.getAuthentification().getQuestionSecrete()) ;
            Monprofilereponse.setText(myprofile.getAuthentification().getReponceQuestion()) ;

            Modiferprofileprenom.setText(myprofile.getPrenom());
            Modiferprofilenom.setText(myprofile.getNom());
            Modiferprofiletele.setText(Integer.toString(myprofile.getTele()));
            Modiferprofileadresse.setText(myprofile.getAdresse());
            Modiferprofilemail.setText(myprofile.getMail());
            Modiferprofilepay.setText(myprofile.getPays());
            Modiferprofilenaissance.setValue(Adaptateur.StringToLocalDate(myprofile.getNaissance()));
            if( "Homme".equals(myprofile.getSexeString())){
                 Modiferprofilehomme.setSelected(true);
            }
            else{
                 Modiferprofilefemme.setSelected(true);
            }
            
            //Panel modifier mot de passe
            ModiferPassQuestion.setPromptText(myprofile.getAuthentification().getQuestionSecrete());
            ModiferPassReponce.setText(myprofile.getAuthentification().getReponceQuestion());
            
            
        }
        else{
            SD.ShowAletDialog();
        }
        
        ButtonSavePofile.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SavePofile();
            }
        });
        
        ButtonSavePassword.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SavePassword();
            }
        });
        
    }
    
    private void SavePofile() 
    {
        if( clt.ContrMinCaractaire(Modiferprofilenom, erreurnom, 3) &&
            clt.ContrMinCaractaireNotnull(Modiferprofileprenom, erreurprenom, 3) && 
            clt.ContrNumeriqueNotnull(Modiferprofiletele, erreurtele) &&
            clt.ContrMinCaractaireNotnull(Modiferprofileadresse, erreuradresse, 5) && 
            clt.ContrNullDatePicker(Modiferprofilenaissance, erreurnaissance) &&
            clt.ContrMinCaractaireNotnull(Modiferprofilepay, erreurpay, 3) 
            )
        {
            myprofile.setNom(Modiferprofilenom.getText());
            myprofile.setPrenom(Modiferprofileprenom.getText());
            myprofile.setMail(Modiferprofilemail.getText());
            myprofile.setTele(Integer.parseInt(Modiferprofiletele.getText()));
            myprofile.setAdresse(Modiferprofileadresse.getText());
            myprofile.setPays(Modiferprofilepay.getText());
            myprofile.setSexe(Integer.parseInt(groupesexe.getSelectedToggle().getUserData().toString()));
            myprofile.setNaissance(Modiferprofilenaissance.getValue().toString());
            
            //mettre a jour le profile
            boolean result = profiledb.updateProfile(User.idprofile, myprofile);
            
            //cas d'écheque de connexion
            if(!result){
                SD.ShowAletDialog();
            }else{
                FadeTransition ft = new FadeTransition(Duration.millis(400), Modiferprofilegridpane);
                ft.setFromValue(1.0);
                ft.setToValue(0.0);
                ft.play();
                ft.setOnFinished(new EventHandler<ActionEvent>() {
                    //message de succés    
                    @Override
                    public void handle(ActionEvent event) {
                        ButtonSavePofile.setVisible(false);
                        Image success = new Image("/Public/icon/successfully.png");

                        ImageView iv1 = new ImageView();
                        iv1.setImage(success);

                        Text text= new Text();
                        text.setText("la modification a été effectuée avec succès");
                        text.setFont(Font.loadFont(getClass().getResourceAsStream("/Public/Fonts/Raleway-SemiBold.ttf"), 20));

                        StackPane stackpane = new StackPane();
                        stackpane.setLayoutX(140);
                        stackpane.setLayoutY(140);
                        stackpane.setPrefHeight(200);
                        stackpane.setPrefWidth(200);
                        stackpane.getChildren().add(iv1);
                        stackpane.getChildren().add(text);
                        StackPane.setAlignment(text, Pos.BOTTOM_CENTER);

                        AnchorPaneModierProduit.setLeftAnchor(stackpane, 83.0);
                        AnchorPaneModierProduit.setRightAnchor(stackpane, 83.0);
                        AnchorPaneModierProduit.setTopAnchor(stackpane,100.0);
                        AnchorPaneModierProduit.setBottomAnchor(stackpane,200.0);       
                        AnchorPaneModierProduit.getChildren().add(stackpane);

                    }
                });
            } 
        }
    }
    
    
    private void SavePassword() 
    {
        if( clt.ContrEqualsNotnull(ModiferPassAncien, erreurAncien, myprofile.getAuthentification().getPassword()) &&
            clt.ContrMinCaractaireNotnull(ModiferPassNouveau, erreurNouveau, 6) &&    
            clt.ContrEqualsNotnull(ModiferPassRepeter, erreurRepeter, ModiferPassNouveau.getText()) &&
            clt.ContrNull(ModiferPassReponce, erreurReponce)
            )
        {
            Authentification authentification = myprofile.getAuthentification();
            authentification.setPassword(ModiferPassNouveau.getText());
            authentification.setQuestionSecrete((String) ModiferPassQuestion.getValue());
            authentification.setReponceQuestion(ModiferPassReponce.getText());
            
            boolean result = profiledb.updateAuthentification(authentification.getIdAuthentification(), authentification);
            
            if(!result){
                SD.ShowAletDialog();
            }
            else{
                //AnchorPaneModiferPass
                FadeTransition ft = new FadeTransition(Duration.millis(400), ModiferPassgridpane);
                ft.setFromValue(1.0);
                ft.setToValue(0.0);
                ft.play();
                ft.setOnFinished(new EventHandler<ActionEvent>() {
                    //message de succés    
                    @Override
                    public void handle(ActionEvent event) {
                        ButtonSavePassword.setVisible(false);
                        
                        Image success = new Image("/Public/icon/successfully.png");

                        ImageView iv1 = new ImageView();
                        iv1.setImage(success);

                        Text text= new Text();
                        text.setText("la modification a été effectuée avec succès");
                        text.setFont(Font.loadFont(getClass().getResourceAsStream("/Public/Fonts/Raleway-SemiBold.ttf"), 20));

                        StackPane stackpane = new StackPane();
                        stackpane.setLayoutX(140);
                        stackpane.setLayoutY(140);
                        stackpane.setPrefHeight(200);
                        stackpane.setPrefWidth(200);
                        stackpane.getChildren().add(iv1);
                        stackpane.getChildren().add(text);
                        StackPane.setAlignment(text, Pos.BOTTOM_CENTER);

                        AnchorPaneModiferPass.setLeftAnchor(stackpane, 83.0);
                        AnchorPaneModiferPass.setRightAnchor(stackpane, 83.0);
                        AnchorPaneModiferPass.setTopAnchor(stackpane,100.0);
                        AnchorPaneModiferPass.setBottomAnchor(stackpane,200.0);       
                        AnchorPaneModiferPass.getChildren().add(stackpane);
                        
                        
                    }
                });
            }
        }
    }
    /*@FXML
    private void UpdatePasswordButtonAction(ActionEvent event) {
        
        if(ModiferPassAncien.getText().equals(myprofile.getAuthentification().getPassword())){
            erreurAncien.setText("");
            ModiferPassAncien.setStyle("-fx-border-color: transparent;");
            
            if(ModiferPassNouveau.getText().length()<6){
                erreurNouveau.setText("Mot de passe doit dépasser 6 caractère");
                ModiferPassNouveau.setStyle("-fx-border-color:#f20606;");
            }
            else{
                erreurNouveau.setText("");
                ModiferPassNouveau.setStyle("-fx-border-color: transparent;");
                
                if(ModiferPassNouveau.getText().equals(ModiferPassRepeter.getText())){
                    ModiferPassRepeter.setStyle("-fx-border-color: transparent;");
                    erreurRepeter.setText("");
                    
                    if(ModiferPassReponce.getText().length()<3){
                        ModiferPassReponce.setStyle("-fx-border-color: #f20606;");
                        erreurReponce.setText("la réponse doit dépasser 2 caractère");
                    }
                    else{
                        ModiferPassReponce.setStyle("-fx-border-color: transparent;");
                        erreurReponce.setText("");
                        
                       
                        //update password
                        updateprofile.getAuthentification().setPassword(ModiferPassNouveau.getText());
                        updateprofile.getAuthentification().setQuestionSecrete(ModiferPassQuestion.getValue().toString());
                        updateprofile.getAuthentification().setReponceQuestion(ModiferPassReponce.getText());
                        boolean result=profiledb.updatePassword(User.idprofile, updateprofile);
                        if(!result){
                            SD.ShowAletDialog();
                        }
                        else{
                            //AnchorPaneModiferPass
                            FadeTransition ft = new FadeTransition(Duration.millis(400), ModiferPassgridpane);
                            ft.setFromValue(1.0);
                            ft.setToValue(0.0);
                            ft.play();
                            ft.setOnFinished(new EventHandler<ActionEvent>() {
                                //message de succés    
                                @Override
                                public void handle(ActionEvent event) {
                                    Image success = new Image("/Public/icon/successfully.png");

                                    ImageView iv1 = new ImageView();
                                    iv1.setImage(success);

                                    Text text= new Text();
                                    text.setText("la modification a été effectuée avec succès");
                                    text.setFont(Font.loadFont(getClass().getResourceAsStream("/Public/Fonts/Raleway-SemiBold.ttf"), 20));

                                    StackPane stackpane = new StackPane();
                                    stackpane.setLayoutX(140);
                                    stackpane.setLayoutY(140);
                                    stackpane.setPrefHeight(200);
                                    stackpane.setPrefWidth(200);
                                    stackpane.getChildren().add(iv1);
                                    stackpane.getChildren().add(text);
                                    StackPane.setAlignment(text, Pos.BOTTOM_CENTER);

                                    AnchorPaneModiferPass.setLeftAnchor(stackpane, 83.0);
                                    AnchorPaneModiferPass.setRightAnchor(stackpane, 83.0);
                                    AnchorPaneModiferPass.setTopAnchor(stackpane,100.0);
                                    AnchorPaneModiferPass.setBottomAnchor(stackpane,200.0);       
                                    AnchorPaneModiferPass.getChildren().add(stackpane);

                                }
                            });
                        }
                        
                    }
                }
                else{
                    ModiferPassRepeter.setStyle("-fx-border-color:#f20606;");
                    erreurRepeter.setText("Mot de passe incorrect");
                }
            }
        }
        else{
            erreurAncien.setText("Password incorrect");
            ModiferPassAncien.setStyle("-fx-border-color:#f20606;");
        }
        
    }*/
    
    
    
    
    
}
