using AduSkin.Controls.Metro;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
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.Shapes;
using System.Linq;
using System.Windows.Threading;
using JianGongYun.TRTC.Components;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace JianGongYun.TRTC.Windows
{
    /// <summary>
    /// LiveWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LiveWindow : MetroWindow
    {
        [DllImport("Kernel32.dll", EntryPoint = "AttachConsole", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern void AttachConsole(int dwProcessId);

        ViewModels.LiveWindowViewModel LiveWindowViewModel;
        ViewModels.SettingWindowViewModel SettingWindowViewModel;
        public LiveWindow()
        {
            InitializeComponent();
            NoticeManager.Initialize();
            AttachConsole(-1);//把进程挂在控制台，通过命令行启动程序可以看到控制台输出
            LiveWindowViewModel = new ViewModels.LiveWindowViewModel();
            SettingWindowViewModel = ViewModels.SettingWindowViewModel.GetInstance();
            this.DataContext = LiveWindowViewModel;
            BorderBrush = new SolidColorBrush(color: Color.FromRgb(42, 43, 48));//窗口标题背景颜色
        }




        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            //颜色前台设置无效，手动调用才行
            var color = (SolidColorBrush)(new BrushConverter().ConvertFrom("#cccccc"));
            Rad1.Foreground = color;
            Rad2.Foreground = color;
            Rad3.Foreground = color;
            Rad4.Foreground = color;
            //LiveClassroom.PauseAllView(false);//切前台启动实时预览渲染

        }

        protected override void OnDeactivated(EventArgs e)
        {
            base.OnDeactivated(e);
            //LiveClassroom.PauseAllView(true);//切后台停止实时预览渲染
        }

        private Window settingWindow;
        //设置按钮
        private void Setting_Btn_Click(object sender, RoutedEventArgs e)
        {
            settingWindow = SettingWindow.GetInstance();
            settingWindow.Closed += (a, b) => settingWindow = null;
            settingWindow.Show();
            if (settingWindow.WindowState != WindowState.Normal)
            {
                settingWindow.WindowState = WindowState.Normal;
            }
            settingWindow.Topmost = true;
        }

        protected override void OnClosed(EventArgs e)
        {
            if (settingWindow != null)
            {
                settingWindow.Close();
            }
            base.OnClosed(e);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            LiveClassroom.StopMic();
            if (LiveWindowViewModel.IsLive)
            {
                LiveClassroom.StopVideoMain(AfterLiveViewWrap);
                LiveClassroom.StopVideoSub(AfterLiveSubViewWrap);
                LiveClassroom.StopMic();
            }
            else
            {
                LiveClassroom.StopVideoMain(BeforeLiveViewWrap);
                LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);
            }
            base.OnClosing(e);
        }

        static Action onEnd = default;
        /// <summary>
        /// 开始/结束直播
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartLive_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as AduFlatButton;
            var start = Convert.ToBoolean(btn.Tag);
            if (start)//开始直播
            {
                if (SettingWindowViewModel.DiskSize <= ViewModels.SettingWindowViewModel.DiskWarningSize)
                {
                    var res = AduMessageBox.Show("磁盘剩余空间不足，请选择其他磁盘", "提醒");
                    return;
                }

                //停止预览
                LiveClassroom.StopMic();
                LiveClassroom.StopVideoMain(BeforeLiveViewWrap);
                LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);

                this.Dispatcher.Invoke(new Action(() =>
                {
                    btn.Type = AduSkin.Controls.FlatButtonSkinEnum.warning;
                    btn.Content = "直播倒计时";
                }));
                StartCountdown(() =>
                {
                    LiveWindowViewModel.IsLive = start;
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        btn.Type = AduSkin.Controls.FlatButtonSkinEnum.info;
                        btn.Content = "开始直播";
                    }));

                    //开始直播
                    if (LiveWindowViewModel.LiveType == Models.LiveTypeEnum.CameraAndScreen || LiveWindowViewModel.LiveType == Models.LiveTypeEnum.OnlyCamera)
                    {
                        LiveClassroom.StartVideoMain(AfterLiveViewWrap);
                    }
                    if (LiveWindowViewModel.LiveType == Models.LiveTypeEnum.CameraAndScreen || LiveWindowViewModel.LiveType == Models.LiveTypeEnum.OnlyScreen)
                    {
                        LiveClassroom.StartVideoSub(AfterLiveSubViewWrap);
                    }
                    LiveClassroom.StartMic();
                    LiveClassroom.SetMicMute(false);
                    LiveClassroom.VideoRecordTask(ref onEnd);//启动录制

                }, SettingWindowViewModel.ScreenRecordingCountdown);
            }
            else
            {
                LiveWindowViewModel.IsLive = start;
                onEnd?.Invoke();
                //停止直播
                LiveClassroom.StopMic();
                LiveClassroom.StopVideoMain(AfterLiveViewWrap);
                LiveClassroom.StopVideoSub(AfterLiveSubViewWrap);
            }

        }

        /// <summary>
        /// 开始倒计时
        /// </summary>
        public void StartCountdown(Action countdownEnd, int time = 10)
        {
            CountdownEnd = countdownEnd;
            count = time;
            this.Dispatcher.Invoke(new Action(() =>
            {
                CountdownWrap.Visibility = Visibility.Visible;
            }));
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        /// <summary>
        /// 倒计时结束执行
        /// </summary>
        Action CountdownEnd;
        /// <summary>
        /// 倒计时时间
        /// </summary>
        private int count;
        /// <summary>
        /// 创建Timer对象
        /// </summary>
        private DispatcherTimer timer = null;
        private void timer_Tick(object sender, EventArgs e)
        {
            if (count == 0)
            {
                timer.Stop();
                timer = null;
                this.Dispatcher.Invoke(new Action(() =>
                {
                    CountdownWrap.Visibility = Visibility.Hidden;
                }));
                CountdownEnd?.Invoke();
                //count = 10;
                //timer.Start();
            }
            else
            {
                CountdownControl txt = new CountdownControl(this.CountdownWrap, this);
                txt.TxtValue = count.ToString();
                txt.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                txt.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                this.CountdownWrap.Children.Add(txt);
                count--;
            }

        }

        private void Tpye_Click(object sender, RoutedEventArgs e)
        {
            switch (LiveWindowViewModel.LiveType)
            {
                case Models.LiveTypeEnum.CameraAndScreen:
                    //LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);//停止屏幕分享(直播中SDK再次获取窗口列表会卡死)
                    LiveWindowViewModel.ShowShareScreenList = true;
                    this.Dispatcher.Invoke(new Action(() => LiveWindowViewModel.LoadAllScreen()));
                    break;
                case Models.LiveTypeEnum.OnlyScreen:
                    //LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);//停止屏幕分享(直播中SDK再次获取窗口列表会卡死)
                    LiveClassroom.StopVideoMain(BeforeLiveViewWrap); //停止摄像头分享
                    LiveWindowViewModel.ShowShareScreenList = true;
                    this.Dispatcher.Invoke(new Action(() => LiveWindowViewModel.LoadAllScreen()));
                    break;
                case Models.LiveTypeEnum.OnlyCamera:
                    LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);//停止屏幕分享
                    LiveClassroom.StartVideoMain(BeforeLiveViewWrap);
                    break;
                case Models.LiveTypeEnum.OnlyAudio:
                    LiveClassroom.StopVideoMain(BeforeLiveViewWrap);//停止摄像头分享
                    LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);//停止屏幕分享
                    break;
                default:
                    break;
            }
        }

        private void CloseShareList_Click(object sender, RoutedEventArgs e)
        {
            LiveWindowViewModel.ShowShareScreenList = false;
        }

        private void ShareList_Selected(object sender, RoutedEventArgs e)
        {
            CloseShareList_Click(sender, e);
            if (LiveWindowViewModel.ScreenRunning)
            {
                LiveClassroom.SelectVieoSub();
            }
            else
            {
                if (LiveWindowViewModel.IsLive)//预览和直播是不同的容器
                {
                    LiveClassroom.StartVideoSub(AfterLiveSubViewWrap);
                }
                else
                {
                    LiveClassroom.StartVideoSub(BeforeLiveSubViewWrap);
                }
            }
            if (LiveWindowViewModel.LiveType == Models.LiveTypeEnum.CameraAndScreen)
            {
                if (LiveWindowViewModel.IsLive)//预览和直播是不同的容器
                {
                    LiveClassroom.StartVideoMain(AfterLiveViewWrap);
                }
                else
                {
                    LiveClassroom.StartVideoMain(BeforeLiveViewWrap);
                }
            }
        }

        private void ChangeWin_Click(object sender, RoutedEventArgs e)
        {
            LiveWindowViewModel.ShowShareScreenList = true;
            this.Dispatcher.Invoke(new Action(() => LiveWindowViewModel.LoadAllScreen()));
        }

        private void SetMute_Click(object sender, RoutedEventArgs e)
        {
            LiveClassroom.SetMicMute(null);
            NoticeManager.NotifiactionShow.AddNotifiaction(new NotifiactionModel()
            {
                Title = "提醒",
                Content = $"{(LiveWindowViewModel.MicMute ? "设置" : "取消")}静音成功"
            });
        }

        private void SetCamera_Click(object sender, RoutedEventArgs e)
        {
            if (LiveWindowViewModel.CameraRunning)
            {
                LiveClassroom.StopVideoMain(AfterLiveViewWrap);
            }
            else
            {
                LiveClassroom.StartVideoMain(AfterLiveViewWrap);
            }
            NoticeManager.NotifiactionShow.AddNotifiaction(new NotifiactionModel()
            {
                Title = "提醒",
                Content = $"{(LiveWindowViewModel.CameraRunning ? "开启" : "关闭")}摄像头成功"
            });
        }
        private void SetScreen_Click(object sender, RoutedEventArgs e)
        {
            if (LiveWindowViewModel.ScreenRunning)
            {
                LiveClassroom.StopVideoSub(AfterLiveSubViewWrap);
            }
            else
            {
                if (LiveWindowViewModel.CurrentShareScreen == null)//没选择过窗口需要选一次
                {
                    LiveWindowViewModel.ShowShareScreenList = true;
                    this.Dispatcher.Invoke(new Action(() => LiveWindowViewModel.LoadAllScreen()));
                }
                LiveClassroom.StartVideoSub(AfterLiveSubViewWrap);
            }
            NoticeManager.NotifiactionShow.AddNotifiaction(new NotifiactionModel()
            {
                Title = "提醒",
                Content = $"{(LiveWindowViewModel.ScreenRunning ? "开启" : "关闭")}屏幕分享成功"
            });
        }
    }
}
