using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Widget;

using System;
using System.Collections.Generic;

using Umk.Ntpp;

namespace Tcp
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true,
        WindowSoftInputMode = Android.Views.SoftInput.StateHidden)]
    public class MainActivity : AppCompatActivity
    {
        private TextView tvLokalneAdresyIp, tvStan;
        private EditText etAdres, etPort, etTekst;
        private Button btnPolacz, btnRozlacz, btnWyslij;        
        private ListView lvOdebraneWiadomosci;

        private NtppClient ntppClient;

        private void pokażAdresyIp()
        {
            List<string> ips = Tcp.AdresyIP.PobierzAdresyIp();
            string sips = "";
            foreach (string ip in ips) sips += ip + "\n";
            tvLokalneAdresyIp.Text = sips.TrimEnd('\n');
        }

        protected override void OnCreate(Bundle savedInstanceState)
        {            
            base.OnCreate(savedInstanceState);                        
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            tvLokalneAdresyIp = FindViewById<TextView>(Resource.Id.tvLokalneAdresyIp);
            
            etAdres = FindViewById<EditText>(Resource.Id.etAdres);
            etPort = FindViewById<EditText>(Resource.Id.etPort);
            btnPolacz = FindViewById<Button>(Resource.Id.btnPolacz);
            btnRozlacz = FindViewById<Button>(Resource.Id.btnRozlacz);
            tvStan = FindViewById<TextView>(Resource.Id.tvStan);

            etTekst = FindViewById<EditText>(Resource.Id.etTekst);
            btnWyslij = FindViewById<Button>(Resource.Id.btnWyslij);

            lvOdebraneWiadomosci = FindViewById<ListView>(Resource.Id.lvOdebraneWiadomosci);

            btnPolacz.Click += btnPolacz_Click;
            btnRozlacz.Click += btnRozlacz_Click;
            btnWyslij.Click += btnWyslij_Click;

            pokażAdresyIp();

            ntppClient = new NtppClient();
            ntppClient.StateChanged += ntppClient_StateChanged;
            ntppClient.TextReceived += ntppClient_TextReceived;
        }

        private void ntppClient_StateChanged(object sender, NtppClient.StateChangedEventArgs e)
        {
            Action a = () => { tvStan.Text = e.NewState.ToString(); };
            this.RunOnUiThread(a);
        }

        private List<string> odebraneWiadomości = new List<string>();

        private void pokażOdebraneWiadomości()
        {
            try
            {
                ArrayAdapter<string> adapter = new ArrayAdapter<string>(
                    this,
                    Android.Resource.Layout.SimpleExpandableListItem1,
                    odebraneWiadomości);
                lvOdebraneWiadomosci.Adapter = adapter;
                //scroll down to end
                lvOdebraneWiadomosci.Post(() => lvOdebraneWiadomosci.SetSelection(adapter.Count - 1));
            }
            catch (Exception exc)
            {
                Toast.MakeText(this, "Błąd: " + exc.Message, ToastLength.Long).Show();
            }
        }

        private void ntppClient_TextReceived(object sender, NtppClient.TextReceivedEventArgs e)
        {
            odebraneWiadomości.Add(e.ReceivedFrom.Hostname + " (" + DateTime.Now.ToString() + "): " + e.ReceivedText);
            Action a = () => { pokażOdebraneWiadomości(); };
            this.RunOnUiThread(a);
        }

        private void btnPolacz_Click(object sender, System.EventArgs e)
        {
            try
            {
                NtppConnectionData connectionData = new NtppConnectionData()
                {
                    Hostname = etAdres.Text,
                    Port = Convert.ToInt32(etPort.Text)
                };
                ntppClient.Connect(connectionData);
            }
            catch(Exception exc)
            {
                Toast.MakeText(this, "Błąd: " + exc.Message, ToastLength.Long).Show();
            }
        }

        private void btnRozlacz_Click(object sender, System.EventArgs e)
        {
            try
            {
                ntppClient.Disconnect();
            }
            catch (Exception exc)
            {
                Toast.MakeText(this, "Błąd: " + exc.Message, ToastLength.Long).Show();
            }
        }

        private void btnWyslij_Click(object sender, System.EventArgs e)
        {
            ntppClient.SendText(etTekst.Text);
        }

        protected override void OnDestroy()
        {
            ntppClient.StateChanged -= ntppClient_StateChanged;
            ntppClient.TextReceived -= ntppClient_TextReceived;

            btnRozlacz_Click(this, EventArgs.Empty);

            base.OnDestroy();
        }
    }
}