﻿using System.Windows;
using System.Windows.Controls;
using Helpers;
using SecureCommunicationComponent;
using SecureCommunicationComponent.Exceptions;

namespace PoliceDispatcherClient
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public delegate void ToUiThread(Control control, string message);

        private readonly Communicator _communicator;
        private int _calls, _received;
        private Logs _logForm;
        public MainWindow()
        {
            InitializeComponent();
            DataContext= new Cscie33Legacy();
            _communicator = new Communicator();
            _communicator.CompletedTask += CommunicatorCompletedTask;
             _logForm = new Logs();
        }

        private void CommunicatorCompletedTask(object sender, PrivateTaskEventArgs e)
        {
            var message = $"PROCESSED: Message in Thread: {e.ThreadId}|{e.Message}";

            Dispatcher.InvokeIfNecessary(() =>
            {
                _received++;
                LblReceived.Content = _received.ToString();
                LogHelper.Log(message.Split('|')[0]);
                MessageBox.Show(message.Split('|')[1]);
            });
        }

        private void BtnLog_Click(object sender, RoutedEventArgs e)
        {
            _logForm = new Logs();
            _logForm.Show();
        }

        private void BtnCall_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _calls++;
                LblCalls.Content = _calls.ToString();
                _communicator.SendAlert(TxtAddress.Text, TxtOfficer.Text);
            }
            catch (SecureCommunicationException exception)
            {
                LogHelper.Log(exception);
                MessageBox.Show($@"The following error has ocurred: {exception.Message}", @"Error", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
    }
}