using Microsoft.AspNetCore.Mvc.ModelBinding;
using qtc_net_client_2.Controls;
using qtc_net_client_2.Services;
using QtCNETAPI.Dtos.User;
using QtCNETAPI.Events;
using QtCNETAPI.Models;
using QtCNETAPI.Services.ApiService;
using QtCNETAPI.Services.GatewayService;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace qtc_net_client_2.Forms
{
    public partial class DirectMessage : Form
    {
        private IGatewayService _gatewayService;
        private IApiService _apiService;
        private QtCNETAPI.Models.Message? InitMessage;
        private AudioService AudioService = new();
        public UserInformationDto User { get; set; }
        public ObservableCollection<string> Messages { get; set; }
        public DirectMessage(IGatewayService gatewayService, IApiService apiService, UserInformationDto user, QtCNETAPI.Models.Message? initMsg = null)
        {
            _gatewayService = gatewayService;
            _apiService = apiService;
            User = user;
            Messages = new ObservableCollection<string>();
            InitMessage = initMsg;
            InitializeComponent();
        }

        private async void frmDirectMessage_Load(object sender, EventArgs e)
        {
            lblUsername.Text = User.Username;
            Text = $"QtC.NET Client - Direct Message With {User.Username}";
            Messages.CollectionChanged += Messages_CollectionChanged;

            var pfpRes = await _apiService.GetUserProfilePic(User.Id);
            if(pfpRes != null && pfpRes.Success && pfpRes.Data != null)
            {
                using var ms = new MemoryStream(pfpRes.Data);
                using var img = Image.FromStream(ms);
                pbPfp.Image = new Bitmap(img);
            }

            if (InitMessage != null)
            {
                Messages.Add($"{User.Username}: {InitMessage.Content}");
                AudioService.PlaySoundEffect("sndDirectMsg");
            }
        }

        private async void btnSend_Click(object sender, EventArgs e)
        {
            if (rtxtChatbox.InvokeRequired)
            {
                await rtxtChatbox.Invoke(async delegate ()
                {
                    if (!string.IsNullOrEmpty(rtxtChatbox.Text))
                    {
                        await _gatewayService.SendDirectMessageAsync(User, new QtCNETAPI.Models.Message { Content = rtxtChatbox.Text, AuthorId = _apiService.CurrentUser.Id });
                        Messages.Add($"{_apiService.CurrentUser.Username}: {rtxtChatbox.Text}");
                        rtxtChatbox.Clear();
                        AudioService.PlaySoundEffect("sndSendClick");
                    }
                });
            }
            else
            {
                if (!string.IsNullOrEmpty(rtxtChatbox.Text))
                {
                    await _gatewayService.SendDirectMessageAsync(User, new QtCNETAPI.Models.Message { Content = rtxtChatbox.Text, AuthorId = _apiService.CurrentUser.Id });
                    Messages.Add($"{_apiService.CurrentUser.Username}: {rtxtChatbox.Text}");
                    rtxtChatbox.Clear();
                    AudioService.PlaySoundEffect("sndSendClick");
                }
            }
        }

        private void rtxtChatbox_KeyPress(object sender, KeyEventArgs e)
        {
            // mimick clicking send
            if (e.KeyCode == Keys.Enter)
                btnSend_Click(sender, e);
        }

        private void Messages_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems.Count > 0)
            {
                if (InvokeRequired)
                {
                    Invoke(delegate ()
                    {
                        var msg = e.NewItems.Cast<string>().FirstOrDefault();

                        var ctrl = new ChatMessageControlMinimal()
                        {
                            Username = msg!.Split(':')[0],
                            Message = msg!.Split(":")[1].Trim(),
                        };
                        ctrl.Height = ctrl.CalculateHeight(ctrl.Width);

                        fpnlMessages.Controls.Add(ctrl);
                        fpnlMessages.VerticalScroll.Value = fpnlMessages.VerticalScroll.Maximum;
                        fpnlMessages.PerformLayout();

                        if (!msg!.Contains(_apiService.CurrentUser.Username)) AudioService.PlaySoundEffect("sndMessage");
                    });
                }
                else
                {
                    var msg = e.NewItems.Cast<string>().FirstOrDefault();

                    var ctrl = new ChatMessageControlMinimal()
                    {
                        Username = msg!.Split(':')[0],
                        Message = msg!.Split(":")[1].Trim(),
                    };
                    ctrl.Height = ctrl.CalculateHeight(ctrl.Width);

                    fpnlMessages.Controls.Add(ctrl);
                    fpnlMessages.VerticalScroll.Value = fpnlMessages.VerticalScroll.Maximum;
                    fpnlMessages.PerformLayout();

                    if (!msg!.Contains(_apiService.CurrentUser.Username)) AudioService.PlaySoundEffect("sndMessage");
                }
            }
        }
    }
}
