using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Shared;


namespace ChtiCanon
{


    partial class frmLobby : Form
    {


        ConnectionManager myConnection;
        ListViewItem listviewitem;
        private delegate void NoArgDelegate();
        private int nbPayerReady;
        private int ID;
        private string PseudoChat;


        public frmLobby(ConnectionManager myConnection)
        {
            try
            {
                InitializeComponent();
                this.myConnection = myConnection;
                this.ID = myConnection.ID;
            }
            catch
            {
                PerteConnexion();
            }

        }

        private void PerteConnexion()
        {
            MessageBox.Show("CRITICAL ERROR : connection lose", "Chti'Canon",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
            Environment.Exit(1);


        }






        private void dupPlayer_SelectedItemChanged(object sender, EventArgs e)
        {

        }

        private void RafraichirUser(object o, Users u)
        {
            int nbUser = 0;
            nbPayerReady = 0;
            
            this.Invoke((NoArgDelegate)delegate()
            {
                btnRun.Enabled = false;
                 

                this.lsvPlayer.Items.Clear();

                foreach (User newUser in u.list)
                {
                    nbUser++;
                    this.ID = myConnection.ID;

                    //if (newUser.name != null)
                    //{
                        lsvPlayer.View = View.Details;

                        listviewitem = new ListViewItem(newUser.id.ToString());
                        listviewitem.SubItems.Add(newUser.name);
                        //
                        if (newUser.ready)
                        {

                            listviewitem.SubItems.Add("ready");
                            nbPayerReady++;
                        }
                        else
                        {
                            listviewitem.SubItems.Add("not ready");
                            if (this.ID == newUser.id)
                            {
                                btnReady.Enabled = true;
                                btnCharger.Enabled = false;
                            }

                        }

                        this.lsvPlayer.Items.Add(listviewitem);

                    }


                //}

                if (myConnection.ID == 0 && nbPayerReady == nbUser && nbUser > 1)
                {
                    btnRun.Enabled = true;


                }
            });


        }

        private void btnCharger_Click(object sender, EventArgs e)
        {
            try
            {
                myConnection.send(tbxPseudo.Text);
            }
            catch
            {
                PerteConnexion();
            }
            //usrChat.Enabled = true;
            PseudoChat = ID + " : " + tbxPseudo.Text;
            //usrChat.init(myConnection, PseudoChat);
            gbxChat.Enabled = true;
            btnCharger.Enabled = false;
            this.AcceptButton = btnSend;

        }

        class MyLIst
        {
            public List<int> list;
            public MyLIst(List<int> list)
            {
                this.list = list;
            }
            public void remove()
            {
                lock (list)
                {
                    for (int i = list.Count; i >= 0; i--) list.Remove(i);
                }
            }

        }

        private void frmLobby_Load(object sender, EventArgs e)
        {
            myConnection.users += RafraichirUser;
            myConnection.game += PlayGame;
            myConnection.message += RafraichirChat;
            ColumnHeader columnheader;		// Utilisé pour créer les titres des colonnes.

            lsvPlayer.View = View.Details;

            // Créer des titres de colonne pour les données. 
            columnheader = new ColumnHeader();
            columnheader.Text = "Id";
            this.lsvPlayer.Columns.Add(columnheader);

            columnheader = new ColumnHeader();
            columnheader.Text = "Name";
            this.lsvPlayer.Columns.Add(columnheader);

            columnheader = new ColumnHeader();
            columnheader.Text = "Ready";
            this.lsvPlayer.Columns.Add(columnheader);

            this.lsvPlayer.Columns[0].Width = (lsvPlayer.Width - 4) / 3;
            this.lsvPlayer.Columns[1].Width = (lsvPlayer.Width - 4) / 3;
            this.lsvPlayer.Columns[2].Width = (lsvPlayer.Width - 4) / 3;
        }


        private void tbxPseudo_TextChanged(object sender, EventArgs e)
        {
            if ((tbxPseudo.Text.Trim()) != "")
            {
                btnCharger.Enabled = true;
                this.AcceptButton = btnCharger;
            }
            else
                btnCharger.Enabled = false;
        }

        private void btnReady_Click(object sender, EventArgs e)
        {
            btnCharger.Enabled = false;
            tbxPseudo.Enabled = false;
            btnReady.Enabled = false;
            try
            {
                myConnection.send(true);
            }
            catch
            {
                PerteConnexion();
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                myConnection.send(new Start());
            }
            catch
            {
                PerteConnexion();
            }

        }

        private void PlayGame(object o, Game g)
        {
            this.Invoke((NoArgDelegate)delegate()
            {
                gbxJeux.Enabled = false;
                string[] names = new string[lsvPlayer.Items.Count];
                for (int i = 0; i < lsvPlayer.Items.Count; i++)
                    // Reprend les noms dans l'ordre de l'ID. Il ne doit pas y avoir de trou!
                    names[int.Parse(lsvPlayer.Items[i].SubItems[0].Text)] = lsvPlayer.Items[i].SubItems[1].Text;
                new Program.GameThread(myConnection, g, ID, names);
            });
        }



        private void frmLobby_FormClosing(object sender, FormClosingEventArgs e)
        {
            //e.Cancel = true;

            if (myConnection != null)
                myConnection.Close();
            Environment.Exit(0);
            //gt.Connection.send(new Shared.Close());
            //System.Environment.Exit(0);

        }


        private void sendText()
        {
            string pseudo = ID +" : " +tbxPseudo.Text;
            if ((tbxChat.Text).Trim() != "")
            {
                try
                {
                    Shared.Message texte = new Shared.Message(pseudo, tbxChat.Text);
                    myConnection.send(texte);
                }
                catch
                {
                    PerteConnexion();
                }
                btnSend.Enabled = false;
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            sendText();
            tbxChat.Text = "";


         
        }

        private void tbxChat_TextChanged(object sender, EventArgs e)
        {

            if ((tbxChat.Text).Trim() != "")
            {
                btnSend.Enabled = true;
            }
            else
            {
                btnSend.Enabled = false;
            }
        }

        private void RafraichirChat(object o, Shared.Message m)
        {
            this.Invoke((NoArgDelegate)delegate()
            {



                //rtbox_SendMessage.ForeColor = Color.Red;
                // Ajoute la commande à l'historique
                //rtbChat.ForeColor = tabCouleur[ID_couleur];
                rtbChat.Text += m.ToString() + "\n";
                rtbChat.Focus();
                rtbChat.SelectionLength = 0;
                rtbChat.SelectionStart = (rtbChat.Text.Length - 1);
                rtbChat.ScrollToCaret();
                rtbChat.ReadOnly = true;
                tbxChat.Focus();


            });
        }
    }
}