/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gamegraphics;

import database.exception.NoAuthorityException;
import java.awt.Color;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JApplet;
import javax.swing.JPanel;
import common.Data;

/**
 *
 * @author Ani
 */
public class WoaleyJApplet extends JApplet implements Runnable{
    private OptionPanel op;
    private WoaleyPanel wp;
    private EndOfGamePanel eog;
    private NoAuthorityPanel noa;
    private SomethingFailedPanel sf;

    private Thread game;
    private Data data;


    @Override
    public void init() {
        try {
           createConnection();
           pickUser();
                try {
                    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {

                        public void run() {
                            createGUI();
                        }
                    });
                } catch (Exception ex) {
                    initSomethingFailedPanel(ex.getMessage());
                }
        } catch (NoAuthorityException noaex) {
            try {
                javax.swing.SwingUtilities.invokeAndWait(new Runnable() {

                    public void run() {
                        createNoAuthorityGUI();
                    }
                });
            } catch (Exception ex) {
                initSomethingFailedPanel(ex.getMessage());
            }
        } catch (Exception ex) {
            initSomethingFailedPanel(ex.getMessage());
        }
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }



    public URLConnection createConnection() throws MalformedURLException, IOException{
        URL urlServlet = new URL(getCodeBase(), "Game");
	URLConnection servletConnection = urlServlet.openConnection();
	servletConnection.setDoInput(true);
	servletConnection.setDoOutput(true);
	servletConnection.setUseCaches(false);
	servletConnection.setRequestProperty("Content-Type","application/x-java-serialized-object");
        return servletConnection;
    }

    private void pickUser() throws NoAuthorityException, IOException, ClassNotFoundException{
        String username = getParameter("username");
        URLConnection servletConnection = createConnection();

	ObjectOutputStream out = new ObjectOutputStream(servletConnection.getOutputStream());
	out.writeObject(username);
	out.flush();
	out.close();

	ObjectInputStream in = new ObjectInputStream(servletConnection.getInputStream());
	String tablename = (String) in.readObject();
	in.close();

        if (tablename==null){
            throw new NoAuthorityException();
        }

        data = new Data(username, tablename);
    }

    private void createGUI(){
        initSettings();
        initOptionPanel();
        initWoaleyPanel();
        initEoGamePanel();
        getContentPane().add(op);
        initThread();
    }

    private void createNoAuthorityGUI(){
        initSettings();
        initNoAuthorityPanel();
        getContentPane().add(noa);
        getContentPane().repaint();
    }

    private void initSettings(){
        setSize(800, 500);
        getContentPane().setBackground(new Color(30, 180, 30));
        getContentPane().setLayout(null);
    }

    private void initOptionPanel(){
        op = new OptionPanel();
    }

    private void initWoaleyPanel(){
        wp = new WoaleyPanel(this);
    }

    private void initEoGamePanel(){
        eog = new EndOfGamePanel();
    }

    private void initNoAuthorityPanel(){
        noa = new NoAuthorityPanel();
    }

   private void initSomethingFailedPanel(String text){
        sf = new SomethingFailedPanel(text);
        getContentPane().removeAll();
        getContentPane().add(sf);
        getContentPane().repaint();
    }

    private void initThread(){
        game = new Thread(this);
        game.start();
    }

    public void run() {
        while(Thread.currentThread()==game){
            try {
                while (op.getOption() == null) {

                }
                initWoaleyPanel();
                wp.startNewGame(op.getOption());
                removePreviousAndAddNextPanel(op, wp);
                getContentPane().add(wp);
                while (wp.getWinnerStatistic() == null) {

                }
                updateUserstatistic();
                eog.setWs(wp.getWinnerStatistic());
                removePreviousAndAddNextPanel(wp, eog);
                while (!eog.isOkclicked()) {

                }
                removePreviousAndAddNextPanel(eog, op);
                op.setOption(null);
                eog.setOkclicked(false);
            } catch (Exception ex) {
                getContentPane().removeAll();
                getContentPane().add(new SomethingFailedPanel(ex.getMessage()));
            }
        }
    }

    private void updateUserstatistic() throws IOException, ClassNotFoundException{
        URLConnection servletConnection = createConnection();

        if (wp.getWinnerStatistic().isWinner()){
            data.setGame(Data.WINNED);
        }
        else if (!wp.getWinnerStatistic().isWinner()){
            data.setGame(Data.LOST);
        }
        else{
            data.setGame(Data.DRAWN);
        }

        ObjectOutputStream out = new ObjectOutputStream(servletConnection.getOutputStream());
	out.writeObject(data);
	out.flush();
	out.close();
        
        ObjectInputStream in = new ObjectInputStream(servletConnection.getInputStream());
	String message = (String) in.readObject();
	in.close();
    }

    private void removePreviousAndAddNextPanel(JPanel remove, JPanel add){
        getContentPane().remove(remove);
        getContentPane().add(add);
        getContentPane().repaint();
    }


    // TODO overwrite start(), stop() and destroy() methods

}
