using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SamaPager_Server
{
    public partial class MainForm : Krypton.Toolkit.KryptonForm
    {
        Server srv { get; set; }
        Thread listenThread { get; set; }
        bool Stop = false;

        public MainForm()
        {
            InitializeComponent();
        }

        private void ListenWorker()
        {
            while (this.Stop == false)
            {
                string result = srv.StartListening();
                this.Invoke((MethodInvoker)delegate
                {
                    logList.Items.Add(result);
                });
            }
            srv.KillServer();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            logList.Items.Add("Welcome to SamaPager Server");
            srv = new Server(IPAddress.Any, 2000);
            statusLabel.Text = "STATUS: " + srv.StartServer();
            listenThread = new Thread(ListenWorker);
            listenThread.Start();
        }

        private void trayShowForm_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void trayExit_Click(object sender, EventArgs e)
        {
            Exit();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                Hide();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Exit();
        }

        private void Exit()
        {
            this.Stop = true;
            Application.Exit();
        }

        private void infoToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var aboutForm = new AboutForm();
            aboutForm.ShowDialog();
        }
    }
}
