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();
            BeforeLiveSubViewWrap.SizeChanged += BeforeLiveSubViewWrap_SizeChanged;
            AfterLiveSubViewWrap.SizeChanged += AfterLiveSubViewWrap_SizeChanged;
            //AttachConsole(-1);//把进程挂在控制台，通过命令行启动程序可以看到控制台输出
            LiveWindowViewModel = new ViewModels.LiveWindowViewModel();
            SettingWindowViewModel = ViewModels.SettingWindowViewModel.GetInstance();
            this.DataContext = LiveWindowViewModel;
            BorderBrush = new SolidColorBrush(color: Color.FromRgb(42, 43, 48));//窗口标题背景颜色
        }

        private void AfterLiveSubViewWrap_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (LiveWindowViewModel.IsLive)
            {
                this.Dispatcher.Invoke(new Action(() => LiveClassroom.ResizeVideoSub(AfterLiveSubViewWrap)));
            }
        }

        private void BeforeLiveSubViewWrap_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!LiveWindowViewModel.IsLive)
            {
                this.Dispatcher.Invoke(new Action(() => LiveClassroom.ResizeVideoSub(BeforeLiveSubViewWrap)));
            }
        }



        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;
        }

        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)
            {

            }
            else
            {
                LiveClassroom.StopVideoMain(BeforeLiveViewWrap);
                LiveClassroom.StopVideoSub(BeforeLiveSubViewWrap);
            }
            base.OnClosing(e);
        }

        /// <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)//开始直播
            {
                //停止预览
                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);

                }, SettingWindowViewModel.ScreenRecordingCountdown);
            }
            else
            {
                LiveWindowViewModel.IsLive = start;
                //停止直播
                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.IsLive && LiveWindowViewModel.ScreenRunning)
            {
                LiveClassroom.SelectVieoSub();
            }
            else
            {
                LiveClassroom.StartVideoSub(BeforeLiveSubViewWrap);
            }
            if (LiveWindowViewModel.LiveType == Models.LiveTypeEnum.CameraAndScreen)
            {
                LiveClassroom.StartVideoMain(BeforeLiveViewWrap);
            }
        }

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