using arTCPService.Shared.Messages;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project.Dialog
{
    public partial class fChat : Form
    {

        arTCPService.Server.Receiver client;
        public fChat(arTCPService.Server.Receiver client_)
        {
            InitializeComponent();
            this.client = client_;
            this.client.DataSend += Svr_DataSend;
            this.client.DataReceived += Svr_DataReceived;
            this.client.ClientDisconnected += Svr_ClientDisconnected;
            this.client.Message += Svr_Message;
            this.FormClosed += FChat_FormClosed;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };

            tbMsg.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) btnSend.PerformClick(); };
            btnSend.Click += (s1, e1) =>
            {
                this.client.SendMessage(new Packet(Header.Message, tbMsg.Text));
                tbMsg.SelectAll();
                tbMsg.Focus();
            };
        }

        private void FChat_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.client.DataSend -= Svr_DataSend;
            this.client.DataReceived -= Svr_DataReceived;
            this.client.ClientDisconnected -= Svr_ClientDisconnected;
            this.client.Message -= Svr_Message;
        }

        private void Svr_DataSend(arTCPService.Server.Receiver arg1, arTCPService.Shared.Messages.Packet arg2)
        {
            if (arg2.header == arTCPService.Shared.Messages.Header.Message)
                addLog("발신:" + arg2.Message);
        }

        private void Svr_Message(arTCPService.Server.Receiver arg1, string arg2, bool arg3)
        {
            addLog("시스템메세지:" + arg2);
        }

        private void Svr_ClientDisconnected(arTCPService.Server.Receiver obj)
        {
            addLog("연결종료");
        }

        private void Svr_DataReceived(arTCPService.Server.Receiver arg1, arTCPService.Shared.Messages.Packet arg2)
        {
            if (arg2.header == arTCPService.Shared.Messages.Header.Message)
            {
                addLog("수신:" + arg2.Message);
            }
        }

        private void fChat_Load(object sender, EventArgs e)
        {
            addLog("채팅이 시작되었습니다 :" + this.client.ID);
        }
        private void InvokeUI(Action action)
        {
            this.Invoke(action);
        }

        void addLog(string m)
        {
            richTextBox1.Invoke(new Action(() =>
            {
                this.richTextBox1.AppendText(m + "\r\n");
                this.richTextBox1.ScrollToCaret();
            }));
        }
    }
}
