package chatapp.Protocol;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

import chatapp.Controller.ChatApp;
import chatapp.Model.DataBase;
import chatapp.Model.MessageHorodate;
import chatapp.Model.Utilisateur;
import chatapp.View.FenetreSession;
import javafx.application.Platform;

public class SessionClavardage extends Thread {
    private Socket link;
    private ChatApp app;
    private Utilisateur u2;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private PropertyChangeSupport pcs;
    private ArrayList<MessageHorodate> derniersMsg; // on met temporairement les derniers msgs pour éviter les pb de synchro inter-threads
    private int SessionID;
    public SessionClavardage(Socket link, ChatApp app) {
        this.setLink(link);
        this.setApp(app);
        try {
            this.setU2(app.getActifUsers().getIPList(link.getInetAddress()));
            this.setOut(new ObjectOutputStream(link.getOutputStream()));
            this.setIn(new ObjectInputStream(link.getInputStream()));
        }catch(Exception e) {
            e.getStackTrace();
        }
        this.derniersMsg = new ArrayList<MessageHorodate>();
        this.SessionID = 2;
        Platform.runLater( () ->
            new FenetreSession(this)
        );
        this.pcs = new PropertyChangeSupport(this);
        this.start();
    }

    public SessionClavardage(Utilisateur u2, ChatApp app) {
        this.setU2(u2);
        this.setApp(app);
        try {
            Socket s = new Socket(u2.getIp(),5000);
            this.setOut(new ObjectOutputStream(s.getOutputStream()));
            this.setIn(new ObjectInputStream(s.getInputStream()));
            this.setLink(s);
        } catch (IOException e) {

            e.printStackTrace();
        }
        this.derniersMsg = new ArrayList<MessageHorodate>();
        this.pcs = new PropertyChangeSupport(this);
        this.app.getDb().CreationTableHistorique("Doudou","Marvel");
        this.start();
        Platform.runLater( () ->
                new FenetreSession(this)
        );
    }


    public void addPropertyChangeListener(PropertyChangeListener pcl){
        this.pcs.addPropertyChangeListener("MessageRecu",pcl);
        this.pcs.addPropertyChangeListener("FinDeLaSession",pcl);
    }

    public void arretSession() {
        MessageHorodate msgh = new MessageHorodate(getU2(),getApp().getMe(),".",2);
        try {
            getOut().writeObject(msgh.toString());
        } catch (IOException e) {
            //e.printStackTrace();
        }
        finally {
            try {
                link.close();
            } catch (IOException e) {

            }
        }
    }
    public void envoiMsg(String msg) {
        MessageHorodate msgh = new MessageHorodate(getU2(),getApp().getMe(),msg,1);
        try {
            getOut().writeObject(msgh.toString());
            app.getDb().ajoutHistorique(u2.getId(), app.getMe().getId(),msg);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public MessageHorodate getDernierMsg() {
        return this.derniersMsg.remove(0);
    }



    public void run() {
        String plaintext = null;
        MessageHorodate msg = null;
        System.out.println("Session demarre");
        app.getDb().CreationTableHistorique(app.getMe().getId(), u2.getId());
        while(true) {
            try {
                plaintext = (String) getIn().readObject();
                msg = MessageHorodate.stringToMessageHorodate(plaintext);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                pcs.firePropertyChange("FinDeLaSession", false, true);
                break;
            }
            if(msg.getType() == 2) {
                pcs.firePropertyChange("FinDeLaSession", false, true);
                try {
                    link.close();
                } catch (IOException e) {
                    break;
                }
                break;
            }
            derniersMsg.add(msg);
            pcs.firePropertyChange("MessageRecu",false,true);

        }
    }

    public ObjectOutputStream getOut() {
        return out;
    }

    public void setOut(ObjectOutputStream out) {
        this.out = out;
    }

    public ObjectInputStream getIn() {
        return in;
    }

    public void setIn(ObjectInputStream in) {
        this.in = in;
    }

    public Socket getLink() {
        return link;
    }

    public void setLink(Socket link) {
        this.link = link;
    }

    public ChatApp getApp() {
        return app;
    }

    public void setApp(ChatApp app) {
        this.app = app;
    }

    public Utilisateur getU2() {
        return u2;
    }

    public void setU2(Utilisateur u2) {
        this.u2 = u2;
    }


    public int getSessionID() {
        return SessionID;
    }

    public void setSessionID(int sessionID) {
        SessionID = sessionID;
    }
}
