using Microsoft.AspNetCore.Components;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TAPI3Lib;
using WK5.Core;
using WK5.Core.Basis.Erweiterungen;
using WK5.Core.Models;
using WK5.Core.Services;

namespace WK5_Blazor.Components.Modals
{
    public partial class TelefonModal
    {
        [Parameter] public string Telefonnummer { get; set; } = String.Empty;
        [Parameter] public bool AllowNumberChange { get; set; } = true;
        [Parameter] public bool AllowLineChange { get; set; } = true;

        private string? SelectedLine { get; set; }
        private bool _callStarted = false;        
#nullable disable
        [CascadingParameter] public AppMitarbeiter Mitarbeiter { get; set; }
#nullable enable

        private List<ITAddress> _lines { get; set; } = new List<ITAddress>();

        private bool CanCall => SelectedLine != null && !_callStarted;
        private bool CanHangup => SelectedLine != null && _callStarted;

        private TAPIService.ActiveCall? SelectedLineCallInfo { get; set; }

        protected override Task OnParametersSetAsync()
        {
            try
            {
                _lines = tapiService.GetLines().ToList();
                int line = tapiService.GetMitarbeiterLine(Mitarbeiter);
                if (tapiService.LineExists(line))
                {
                    SelectedLine = tapiService.GetLine(line)?.DialableAddress;
                }
                else
                {
                    SelectedLine = _lines.OrderBy(x => x.DialableAddress).FirstOrDefault()?.DialableAddress ?? "0";
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error($"{ex}");
            }
            

            return base.OnParametersSetAsync();
        }

        private async Task EndCall()
        {
            if (Int32.TryParse(SelectedLine, out int line))
            {
                if (line > 0 && tapiService.LineExists(line) && !String.IsNullOrWhiteSpace(Telefonnummer))
                {
                    try
                    {
                        tapiService.EndCall(line);
                    }
                    catch (Exception ex)
                    {
                        await jsRuntime.ShowToast(ToastType.error, ex.Message);
                        await LogCall(false, ex.ToString());
                    }
                    finally
                    {
                        _callStarted = false;
                    }
                }
            }
        }

        private async Task Call()
        {
            if (Int32.TryParse(SelectedLine, out int line))
            {
                if (line > 0 && tapiService.LineExists(line) && !String.IsNullOrWhiteSpace(Telefonnummer))
                {
                    try
                    {
                        string? error = tapiService.Call(line, Telefonnummer);
                        if (!String.IsNullOrWhiteSpace(error))
                        {
                            await jsRuntime.ShowToast(ToastType.error, error);
                            await LogCall(false, error);
                        }
                        else
                        {                            
                            _callStarted = true;                            
                        }
                    }
                    catch (Exception ex)
                    {
                        await jsRuntime.ShowToast(ToastType.error, ex.Message);
                        await LogCall(false, ex.ToString());
                        _callStarted = false;
                    }
                }
            }
        }

        private async Task LogCall(bool success, string? reason = null)
        {
            int line = -1;
            if (Int32.TryParse(SelectedLine, out int tmpLine))
            {
                line = tmpLine;
            }

            var log = new CallLog()
            {
                CALL_A_TARGET = Telefonnummer,
                CALL_L_SUCCESS = success,
                CALL_N_LINE = line,
                CALL_N_PERSONAL = Mitarbeiter.PersonalNummer,
                CALL_A_TARGET_PARSED = TAPIService.SanitizePhoneNumber(Telefonnummer),
                CALL_A_REASON = reason
            };

            await log.CreateAsync();
        }       
    }
}
