using C4IT.Logging;
using FasdDesktopUi.Basics.Models;
using FasdDesktopUi.Pages.DetailsPage.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics.UserControls
{
    public partial class DataCanvas : UserControl
    {
        #region Properties
        private cSupportCaseDataProvider dataProvider;
        public cSupportCaseDataProvider DataProvider
        {
            get => dataProvider;
            set
            {
                if (DataCanvasData.GetDetailedDataAsync != null)
                {
                    if (dataProvider != null)
                        dataProvider.HealthCardDataHelper.LoadingHelper.DataRefreshed -= HealthCardDataHelper_DataRefreshed;
                    value.HealthCardDataHelper.LoadingHelper.DataRefreshed += HealthCardDataHelper_DataRefreshed;
                }

                dataProvider = value;
                QuickActionStatusUc.DataProvider = value;
            }
        }

        #region DataCanvasData

        private static void DataCanvasDataChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                var oldData = e.OldValue as cDataCanvasDataModel;
                var newData = e.NewValue as cDataCanvasDataModel;

                if (!(d is DataCanvas _me))
                    return;

                if (_me.dataProvider != null)
                {
                    if (oldData.GetDetailedDataAsync != null)
                        _me.dataProvider.HealthCardDataHelper.LoadingHelper.DataRefreshed -= _me.HealthCardDataHelper_DataRefreshed;

                    if (newData.GetDetailedDataAsync != null)
                        _me.dataProvider.HealthCardDataHelper.LoadingHelper.DataRefreshed += _me.HealthCardDataHelper_DataRefreshed;
                }

                _me.QuickActionStatusUc.CancelQuickAction();

                _me.RecommendationUc.RecommendationData = _me.DataCanvasData.RecommendationData;
                _me.RecommendationUc.CloseButtonClickedAction = _me.CloseDataCanvas;

                if (_me.DataCanvasData.ChartData is null && _me.DataCanvasData.DetailedChartData is null)
                {
                    _me.DetailedDataUc.DetailedInformationData = _me.DataCanvasData.DetailedData;
                    _me.DetailedDataUc.CloseButtonClickedAction = _me.CloseDataCanvas;
                    _me.DynamicChartUc.ChartData = null;
                }
                else if (_me.DataCanvasData.ChartData is null)
                {
                    _me.DynamicChartUc.ChartData = null;
                    _me.DetailedDataUc.DetailedInformationData = null;
                }
                else
                {
                    _me.DynamicChartUc.ChartData = _me.DataCanvasData.ChartData;
                    _me.DetailedDataUc.DetailedInformationData = null;
                    _me.DynamicChartUc.CloseButtonClickedAction = _me.CloseDataCanvas;
                }

                _me.QuickActionStatusUc.QuickActionData = _me.DataCanvasData.QuickActionStatusMonitorData;
                _me.QuickActionStatusUc.CloseButtonClickedAction = _me.CloseDataCanvas;

                _me.QuickActionStatusUc.QuickActionOutputs.Clear();
                _me.QuickActionStatusUc.MeasureValues = null;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public static readonly RoutedEvent DataCanvasWasClosedEvent = EventManager.RegisterRoutedEvent("DataCanvasWasClosed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(DataCanvas));

        public event RoutedEventHandler DataCanvasWasClosed
        {
            add { AddHandler(DataCanvasWasClosedEvent, value); }
            remove { RemoveHandler(DataCanvasWasClosedEvent, value); }
        }

        private void CloseDataCanvas()
        {
            //Visibility = Visibility.Collapsed;

            if (this.Parent is FrameworkElement parentElement)
                parentElement.Visibility = Visibility.Collapsed;

            QuickActionStatusUc.CancelQuickAction();
            RaiseEvent(new RoutedEventArgs(DataCanvasWasClosedEvent));
        }

        public static readonly DependencyProperty DataCanvasDataProperty =
            DependencyProperty.Register("DataCanvasData", typeof(cDataCanvasDataModel), typeof(DataCanvas), new PropertyMetadata(new cDataCanvasDataModel(), new PropertyChangedCallback(DataCanvasDataChangedCallback)));

        public cDataCanvasDataModel DataCanvasData
        {
            get { return (cDataCanvasDataModel)GetValue(DataCanvasDataProperty); }
            set { SetValue(DataCanvasDataProperty, value); }
        }

        #endregion

        #region SubMenuData

        private static void SubMenuDataChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is DataCanvas _me))
                return;
        }

        public static readonly DependencyProperty SubMenuDataProperty =
            DependencyProperty.Register("SubMenuData", typeof(List<cMenuDataBase>), typeof(DataCanvas), new PropertyMetadata(new List<cMenuDataBase>(), new PropertyChangedCallback(SubMenuDataChangedCallback)));

        public List<cMenuDataBase> SubMenuData
        {
            get { return (List<cMenuDataBase>)GetValue(SubMenuDataProperty); }
            set { SetValue(SubMenuDataProperty, value); }
        }

        #endregion

        #region isDetailedLayout

        public static readonly DependencyProperty IsDetailedLayoutProperty =
            DependencyProperty.Register("IsDetailedLayout", typeof(bool), typeof(DataCanvas), new PropertyMetadata(false));

        public bool IsDetailedLayout
        {
            get { return (bool)GetValue(IsDetailedLayoutProperty); }
            set { SetValue(IsDetailedLayoutProperty, value); }
        }

        #endregion

        #endregion

        public DataCanvas()
        {
            InitializeComponent();
        }

        public DataCanvas(bool drawInScrollViewer)
        {
            InitializeComponent();

            if (!drawInScrollViewer)
                return;

            var tempDataCanvas = MainStackPanel;
            ScrollViewer scrollViewer = new ScrollViewer() { Padding = new Thickness(0, 0, 10, 10), VerticalScrollBarVisibility = ScrollBarVisibility.Auto };
            DataCanvasUc.Content = scrollViewer;
            scrollViewer.Content = tempDataCanvas;
        }

        private async void HealthCardDataHelper_DataRefreshed(object sender, EventArgs e)
        {
            await UpdateDataAsync();
        }

        internal async Task UpdateDataAsync()
        {
            try
            {
                var detailedData = DataCanvasData.DetailedData;
                var detailedChartData = DataCanvasData.DetailedChartData;
                var chartData = DataCanvasData.ChartData;

                if (DataCanvasData.GetDetailedDataAsync != null)
                    detailedData = await DataCanvasData.GetDetailedDataAsync.Invoke();

                if (DataCanvasData.GetDatailedChartDataAsync != null)
                    detailedChartData = await DataCanvasData.GetDatailedChartDataAsync.Invoke();

                if (DataCanvasData.GetChartDataAsync != null)
                    chartData = await DataCanvasData.GetChartDataAsync.Invoke();

                var tempDataCanvasData = new cDataCanvasDataModel()
                {
                    GetDetailedDataAsync = DataCanvasData.GetDetailedDataAsync,
                    GetDatailedChartDataAsync = DataCanvasData.GetDatailedChartDataAsync,
                    GetChartDataAsync = DataCanvasData.GetChartDataAsync,
                    RecommendationData = DataCanvasData.RecommendationData,
                    QuickActionStatusMonitorData = DataCanvasData.QuickActionStatusMonitorData,
                };

                if (detailedChartData is null && chartData is null)
                    tempDataCanvasData.DetailedData = detailedData;
                else if (chartData is null)
                    tempDataCanvasData.DetailedChartData = detailedChartData;
                else
                    tempDataCanvasData.ChartData = chartData;

                DataCanvasData = tempDataCanvasData;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public void InsertNewDetailedData(List<object> newDetailedData)
        {
            try
            {
                var tempDetailedData = DetailedDataUc.DetailedInformationData.FullDetailedData;

                if (tempDetailedData == null || tempDetailedData.Count <= 0)
                    return;

                tempDetailedData.Insert(1, newDetailedData);

                DetailedDataUc.DetailedInformationData = new cDetailedDataModel() { Heading = DetailedDataUc.DetailedInformationData.Heading, FullDetailedData = tempDetailedData };
                DetailedDataUc.DetailedDataListView.SelectedItem = DetailedDataUc.DetailedDataListView.Items[0]; // todo: check if best solution with index = 0
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
            }
        }

        private void QuickActionStatusUc_QuickActionFinished(object sender, QuickActionEventArgs e)
        {
            if (Window.GetWindow(this) is Pages.DetailsPage.DetailsPageView)
                InsertNewDetailedData(e.QuickActionResult);
        }

    }
}
