using Http.Core.Contexts;
using PCUT.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using static PCUT.Pages.DataCenterPage;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace PCUT.Pages
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class DesignCenterPage : Page
    {
        private SvgData _svgData => SvgData.Instance;
        DesignCenterViewModel viewModel { get; set; }
        PortSettingViewModel SettingModel { get; set; }
        public DesignCenterPage()
        {
            this.InitializeComponent();
            viewModel = new DesignCenterViewModel();
            SettingModel = new PortSettingViewModel();
            this.DataContext = viewModel;

            var isPermittedEdit = UserContext.Instance.IsPermittedEdit;
            WidthInput.IsEnabled = isPermittedEdit;
            HeightInput.IsEnabled = isPermittedEdit;
            HeightSelector.IsEnabled = !isPermittedEdit;
            if (isPermittedEdit)
            {
                HeightInput.Visibility = Visibility.Visible;
                HeightSelector.Visibility = Visibility.Collapsed;
            }
            else
            {
                HeightInput.Visibility = Visibility.Collapsed;
                HeightSelector.Visibility = Visibility.Visible;
            }
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string itemId = null;
            if (e.Parameter is string id && !string.IsNullOrEmpty(id))
            {
                itemId = id;
                if (itemId != _svgData.ItemId)
                    _svgData.SetData(null);
            }
            else if (_svgData.Data != null)
            {
                itemId = _svgData.ItemId;
            }

            if (!string.IsNullOrEmpty(itemId))
            {
                var loadSuccess = await viewModel.GetCdrFileAsync(itemId);
                if (!loadSuccess)
                {
                    var messageDialog = new MessageDialog("File doesn't exist!");
                    await messageDialog.ShowAsync();
                    return;
                }
                NavigateContentFrame(typeof(EditPage), viewModel);
            }
            var deviceInfo = await GetPortInfos();
            foreach (var info in deviceInfo)
                viewModel.Ports.Add(info);
            if (deviceInfo.Any())
                viewModel.SelectedPortIndex = 0;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //SvgData.Instance.SetData(null);
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CuttingMachines.Text = viewModel.SelectedDeviceName;
            SettingModel.LoadSetting(viewModel.SelectedPortName);
        }

        private void SortFiles_Button(object sender, RoutedEventArgs e)
        {
            NavigateContentFrame(typeof(SvgNestPage), viewModel);
        }

        private void NavigateContentFrame(Type pageType, object param = null, bool isGoBack = false)
        {
            var currentPageType = ContentFrame.Content?.GetType();
            if ((!isGoBack || currentPageType != null) && currentPageType != pageType)
            {
                BackButton.Visibility = pageType == typeof(EditPage) ? Visibility.Collapsed : Visibility.Visible;
                ContentFrame.Navigate(pageType, param);
            }
        }

        private async void CutFiles_Button(object sender, RoutedEventArgs e)
        {
            //if (_svgData.NestedData == null)
            //    NavigateContentFrame(typeof(SvgNestPage), viewModel);
            //else
            //{
                try
                {
                    string selectedPortName = viewModel.SelectedPortName;
                    var dialog = new CutFilesDialog(selectedPortName, SettingModel, viewModel);
                    await dialog.ShowAsync();
                }
                catch
                {

                }
            //}
        }

        private void Back_Click(object sender, RoutedEventArgs e)
        {
            NavigateContentFrame(typeof(EditPage), viewModel, isGoBack: true);
        }

        private async Task<IEnumerable<PortInfo>> GetPortInfos()
        {
            var infos = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());
            if (infos != null && infos.Any())
            {
                var portInfos = new List<PortInfo>();
                foreach (var info in infos.Where(x => x.Id != null))
                {
                    using (var deviceInfo = await SerialDevice.FromIdAsync(info.Id))
                    {
                        if (deviceInfo != null)
                        {
                            portInfos.Add(new PortInfo(deviceInfo.PortName, info.Name));
                        }
                    }
                } 
                return portInfos;
            }
            return Array.Empty<PortInfo>();
        }

        private async void SettingPort_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var categoryEditDialog = new PortSettingDialog(SettingModel);
                await categoryEditDialog.ShowAsync();
                SettingModel.SaveSetting(viewModel.SelectedPortName);
            }
            catch
            {

            }
        }

        private async void Refresh_Click(object sender, RoutedEventArgs e)
        {
            var deviceInfo = await GetPortInfos();
                viewModel.Ports.Clear();
                foreach (var info in deviceInfo)
                    viewModel.Ports.Add(info);
                if (deviceInfo.Any())
                    viewModel.SelectedPortIndex = 0;
            }

        private void TextBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
        {
            args.Cancel = args.NewText.Any(ch => !char.IsDigit(ch) && ch != '.');
        }
    }
}
