package projet_freyja.ihm;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import projet_freyja.math.Base;
import projet_freyja.math.EspaceVectoriel;
import projet_freyja.math.Polynome;
import projet_freyja.math.Vecteur;
import projet_freyja.nombre.Nombre;

public class WindowPoly extends JFrame{
    
    //Attributs
    protected JButton boutonAjout; 
    protected JComboBox polyCrees;
    protected JButton boutonSelection;
    protected JLabel labelPolyCrees;
    protected JTextArea cadreInfo;
    protected JLabel labelCadreInfo;
    protected JButton boutonRacine;
    protected JTextField racine;
    protected JTextField saisieVecteur;
    protected JButton boutonCpculSolution;
    protected JLabel labelRes;
    protected JTextField res;
    protected JButton boutonDerive;
    protected JButton boutonPrimitive;
    protected Polynome p;
    
    public WindowPoly(){
        this.setTitle("Polynômes Window");
        this.setSize(800, 600);
        
        //Création des composants
        boutonAjout = new JButton("Ajouter un polynôme");
        labelPolyCrees = new JLabel("Polynômes disponibles : ");
        polyCrees = new JComboBox();
        boutonSelection = new JButton("Sélectionner");
        labelCadreInfo = new JLabel("Informations de la sélection : ");
        cadreInfo = new JTextArea();
        boutonRacine = new JButton("Racine");
        racine = new JTextField();
        saisieVecteur = new JTextField("Saisissez un vecteur");
        boutonCpculSolution = new JButton("Calculer la solution");
        labelRes = new JLabel("Résultat : ");
        res = new JTextField();
        boutonDerive = new JButton("Calculer dérivé");
        boutonPrimitive = new JButton("Calculer primitive");
        p = null;
        
        //Contenu combobox
        File rep = new File("src\\projet_freyja\\donnees\\polynomes");
        File[] fichiers = rep.listFiles();
        String nomBase = "";
        for(int i = 0; i < fichiers.length; i++){
            //On récupère le nom du fichier sans l'extension
            nomBase = (fichiers[i].getName() != null) ? fichiers[i].getName().substring(0,fichiers[i].getName().indexOf('.')) : "";
            polyCrees.addItem(nomBase);
            nomBase = "";
        }
        
        //Mise sur écoute des boutons
        boutonAjout.addActionListener(new ButtonAjoutListener());
        boutonSelection.addActionListener(new ButtonSelectionListener());
        boutonRacine.addActionListener(new ButtonCalculerRacineListener());
        boutonCpculSolution.addActionListener(new ButtonCalculSolutionListener());
        boutonDerive.addActionListener(new ButtonDeriveListener());
        boutonPrimitive.addActionListener(new ButtonPrimitiveListener());
        
        //Paramétrage des panels
        cadreInfo.setBackground(Color.white);
        cadreInfo.setPreferredSize(new Dimension(400, 400));
        res.setBackground(Color.white);
        res.setPreferredSize(new Dimension(100, 20));
        
        //Mise en place des composants
            //1ere ligne
            JPanel l1 = new JPanel();
            l1.setLayout(new BoxLayout(l1, BoxLayout.LINE_AXIS));
            l1.add(boutonAjout);
            
            //2eme ligne
            JPanel l2 = new JPanel();
            l2.setLayout(new BoxLayout(l2, BoxLayout.LINE_AXIS));
            l2.add(labelPolyCrees);
            l2.add(polyCrees);
            l2.add(boutonSelection);
            
            //3eme ligne
            JPanel l3 = new JPanel();
            l3.setLayout(new BoxLayout(l3, BoxLayout.LINE_AXIS));
            l3.add(labelCadreInfo);
            
            //4eme ligne
            JPanel l4 = new JPanel();
            l4.setLayout(new BoxLayout(l4, BoxLayout.LINE_AXIS));
            l4.add(cadreInfo);
            
            //5eme ligne
            JPanel l5 = new JPanel();
            l5.setLayout(new BoxLayout(l5, BoxLayout.LINE_AXIS));
            l5.add(saisieVecteur);
            l5.add(boutonCpculSolution);
            
            //6eme ligne
            JPanel l6 = new JPanel();
            l6.setLayout(new BoxLayout(l6, BoxLayout.LINE_AXIS));
            l6.add(labelRes);
            l6.add(res);
                        
            //7eme ligne
            JPanel l7 = new JPanel();
            l7.setLayout(new BoxLayout(l7, BoxLayout.LINE_AXIS));
            l7.add(boutonRacine);
            l7.add(racine);
            
            //8eme ligne
            JPanel l8 = new JPanel();
            l8.setLayout(new BoxLayout(l8, BoxLayout.LINE_AXIS));
            l8.add(boutonDerive);
            l8.add(boutonPrimitive);
            
            //Mise en colonne
            JPanel c = new JPanel();
            c.setLayout(new BoxLayout(c, BoxLayout.PAGE_AXIS));
            c.add(l1);
            c.add(l2);
            c.add(l3);
            c.add(l4);
            c.add(l5);
            c.add(l6);
            c.add(l7);
            c.add(l8);
               
        //Ajout du conteneur
        this.getContentPane().add(c);
        
        this.pack();
        //Affichage de la fenêtre
        this.setVisible(true);
    }

      
    //Ecoute des boutons
    class ButtonAjoutListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0){
            WindowDefPoly win = new WindowDefPoly();
        }
    }
    
    class ButtonSelectionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0){
            //On refresh le cadre
            cadreInfo.setText("");
            
            //Lecture de l'espace vectoriel
            ObjectInputStream ois = null;
            try {
                //On tente d'ouvrir le fichier
                ois = new ObjectInputStream(new FileInputStream("src\\projet_freyja\\donnees\\polynomes\\"+polyCrees.getSelectedItem()+".obj"));
            } catch (IOException ex) {
                Logger.getLogger(WindowDefAL.class.getName()).log(Level.SEVERE, null, ex);
            }
            try{
                //On tente de désérialiser le polynome
                p = (Polynome)ois.readObject();
                
                //On affiche les informations
                cadreInfo.append(p.toString());
            } catch (IOException ex) {
                Logger.getLogger(WindowEV.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(WindowEV.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                //On tente de fermer le flux
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(WindowDefAL.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    class ButtonCalculerRacineListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0){
            Nombre[] rac = p.calculerRacines();
            String buff = "{";
            for(int i = 0; i < rac.length; i++){
                if(i == 0){
                    buff += rac[i].toString();
                }
                else{
                    buff += ", "+rac[i].toString();
                }
            }
            buff += "}";
            racine.setText(buff);
        }
    }
    
    class ButtonCalculSolutionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0){
            String vec = saisieVecteur.getText();
            int i = 0;
            int k = 0;
            String nbr;
            int nbrVirgule = 0;
            int c;
            for(int j = 0; j < vec.length(); j++){
                if(vec.charAt(j) == 44){
                    nbrVirgule++;
                }
            }
            String[] coeffS = new String[nbrVirgule + 1];
            double[] coeff = new double[nbrVirgule + 1];
            while(i < vec.length()){ //On parcours la chaine saisie
                if(vec.charAt(i) == 40){ //Si le caractère courant est "("
                    k = 0;
                    nbr = "";
                    c = i+1;
                    while(vec.charAt(c) != 44 && vec.charAt(c) != 41){ //Tant qu'on lit pas ","
                       if(vec.charAt(c) != 40 && vec.charAt(c) != 41){ //On s'assure que c'est pas un mauvais caractère
                            nbr += vec.charAt(c); //On mémorise les chiffres
                       }

                       c++;
                    }    
                    coeff[k] = Double.parseDouble(nbr); //On ajoute les chiffres dans la première case du tableau
                    coeffS[k] = Double.toString(coeff[k]);
                    k++;
                    if(vec.charAt(c) == 41){
              
                        Vecteur v = new Vecteur("Vecteur solution", coeffS);
                        res.setText(p.calculerImage(v).toString());
                    }
                }
                else if(vec.charAt(i) == 44){ //Si le caractère courant est ","
                    if(vec.charAt(i + 1) == 41){
                        Vecteur v = new Vecteur("Vecteur solution", coeffS);
                        res.setText(p.calculerImage(v).toString());
                    }
                    //else{
                        nbr = "";
                        c = i+1;
                        while(vec.charAt(c) != 44 && vec.charAt(c) != 41){//Tant qu'on lit pas "," ou ")"
                            if(vec.charAt(c) != 40){ //On s'assure que c'est pas un mauvais caractère
                                nbr += vec.charAt(c); //On mémorise les chiffres
                            }
                            c++;
                        }
                        coeff[k] = Double.parseDouble(nbr); //On ajoute les chiffres dans le tableau
                        coeffS[k] = Double.toString(coeff[k]);
                        k++;
                        if(vec.charAt(c) == 41){ //Si le caractère courant est ")" => On a lu le vecteur en entier
                            Vecteur v = new Vecteur("Vecteur solution", coeffS);
                            res.setText(p.calculerImage(v).toString());
                        }
                    //}
                }
                i++;//On continue de lire la chaine
            }
        }
    }
    
    class ButtonDeriveListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0){
            p.getDerive();
            cadreInfo.setText("");
            cadreInfo.append(p.toString());
        }
    }
    
    class ButtonPrimitiveListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0){
            p.getPrimitive();
            cadreInfo.setText("");
            cadreInfo.append(p.toString());
        }
    }
}