using ryCommon;
using ryCommon.Pram;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TimeClock.DbOp
{
    public partial class FrmSetting : Form
    {
        public FrmSetting()
        {
            InitializeComponent();
            sound.OnPlayEnd += Sound_OnPlayEnd;
        }

        public DialogResult dr = DialogResult.None;
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            dr = DialogResult.Cancel;
            this.Close();
        }
        bool _RestTip_On = false;
        int _RestInteval = 50;
        int _Rest = 3;
        ryControls.RySetting Setting = new ryControls.RySetting();
        private void FrmSetting_Load(object sender, EventArgs e)
        {
            #region TTS语音朗读
            try
            {
                var spVoices = new COM.SpVoice()
                {
                    Rate = -2,
                    Volume = 100
                };
                var list_Voices = spVoices.GetVoices();
                CbbSpeaker.Items.Clear();
                for (int i = 0; i < list_Voices.Count; i++)
                {
                    CbbSpeaker.Items.Add(list_Voices[i]);
                }
                if (CbbSpeaker.Items.Count > 0) { CbbSpeaker.SelectedIndex = 0; }
            }
            catch (Exception)
            {
            }
            #endregion
            Setting.FileType = SettingType.XML;
            //Setting.FilePath = Application.StartupPath + "\\UserDb\\Setting.dat";
            Setting.SettingXML = Itrycn_Db.GetSetting("Setting", "");
            ryCommon.RyRegedit.RegRoot = Microsoft.Win32.RegistryHive.CurrentUser;
            ChkAutoRun.Checked = ryCommon.RyRegedit.IsAutoRun(Custom.AutoRunName, "\"" + Application.ExecutablePath.Replace("/", "\\") + "\" " + Custom.AutoRunPram);
            Setting.Add("FullScreenTip", ChkFullScreenTip, true);
            Setting.Add("AutoClose", ChkAutoClose, false);
            Setting.Add("AutoCloseMinute", NuAutoCloseMinute, 1);
            Setting.Add("HourlyChime_On", ChkHourlyChime_On, true); 
            Setting.Add("Use24Hours", ChkUse24Hours, true);
            Setting.Add("UseStarHourlyChime", ChkUseStarHourlyChime, true);
            Setting.Add("RestTip_On", ChkRestTip_On, false);
            Setting.Add("RestInteval", NumRestInteval, 50);
            Setting.Add("Rest", NumRest, 3);
            Setting.Add("TipBeforeRest", ChkTipBeforeRest, true);
            Setting.Add("SoundBeforeRest", ChkSoundBeforeRest, true);
            Setting.Add("DelayRestOn", ChkDelayRestOn, true);
            Setting.Add("DelayRestCount", NumDelayRestCount, 3);
            Setting.Add("StopRestByFullScreen", ChkStopRestByFullScreen, true);
            Setting.Add("StopRestByIdle", ChkStopRestByIdle, true);
            Setting.Add("IdleMinute", NumIdleMinute, 3);
            Setting.Add("IdleOver_On", ChkIdleOver_On, true);
            Setting.Add("IdleOverMinute", NumIdleOverMinute, 10);
            Setting.Add("RestMode", CbbRestMode, 0);
            Setting.Add("Speaker", CbbSpeaker, CbbSpeaker.Text);
            Setting.Add("SpeakerVolume", NumSpeakerVolume, 100);
            Setting.Add("SpeakerRate", NumSpeakerRate, 1);
            Setting.Add("RestMusic_On", ChkRestMusic_On, false);
            Setting.Add("MusicType", CbbMusicType, 0);
            Setting.Add("MusicPath", CbbMusicPath, "");
            Setting.Add("SaveSchedule", ChkSaveSchedule, true);
            Setting.Add("MusicVolume", NumMusicVolume, 100);
            Setting.Add("RestOpacity", NumRestOpacity, 90);
            Setting.Read();
            _RestTip_On = ChkRestTip_On.Checked;
            _RestInteval = NumRestInteval.Value.ToInt();
            _Rest = NumRest.Value.ToInt();
            ryCommon.Storage myXML = new Storage();
            myXML.LoadFromXMLText(Setting.SettingXML);
            myXML.SelectNode2("id", "Setting");
            string hours_on= myXML.GetAttrValue("HourOn","");
            var CurrDate= myXML.GetAttrValue("CurrDate",DateTime.Now);
            var week_count= RyDate.GetWeekCount(CurrDate, DateTime.Now);
            ryCommon.ListX list = new ListX(PnlHours)
            {
                MaxColCount = 6,
                spaceX = 30,
                spaceY = 10
            };
            for (int i = 0; i < 24; i++)
            {
                CheckBox chk = new CheckBox
                {
                    AutoSize = true,
                    Text = i.ToString("00") + "时",
                    Tag = i
                };
                chk.CheckedChanged += Chk_CheckedChanged;
                if (hours_on == "") { chk.Checked = true; }
                else if(hours_on.Length==24 && hours_on.Substring(i, 1) == "1") { chk.Checked = true; }
                else { chk.Checked =false; }
                list.Add(chk);
            }
            list.ReDraw2();
            NumCurrWeek.Value = week_count+1;
        }

        private void Chk_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            chk.ForeColor = chk.Checked ? Color.Blue :Color.Black;
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            if(ChkRestTip_On.Checked)
            {
                #region 休息提醒
                if (!NumRestInteval.Value.ToInt().IsInRange(1, 1000))
                {
                    MessageBox.Show("休息提醒时间间隔区间不对。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (!NumRest.Value.ToInt().IsInRange(1, 1000))
                {
                    MessageBox.Show("休息提醒休息时间区间不对。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                } 
                #endregion
            }
            if(ChkRestMusic_On.Checked)
            {
                if (CbbMusicType.SelectedIndex== 0)
                {
                    if (!System.IO.File.Exists(CbbMusicPath.Text))
                    {
                        MessageBox.Show("休息时要播放的音乐不存在。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
                else if (CbbMusicType.SelectedIndex == 1)
                {
                    if (!System.IO.Directory.Exists(CbbMusicPath.Text))
                    {
                        MessageBox.Show("休息时要播放的音乐文件夹不存在。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
            }
            Setting.Save();
            ryCommon.Storage myXML = new Storage();
            myXML.LoadFromXMLText(Setting.SettingXML);
            myXML.SelectNode2("id", "Setting");
            var week_count = NumCurrWeek.Value.ToInt();
            myXML.SetAttrValue("CurrDate", RyDate.GetWeekInfo(DateTime.Now.Date.AddDays(-7 * (week_count - 1))).startDate);
            #region 获取需要报时的时间段
            string HourOn = "";
            string[] hours = new string[24];
            for (int i = 0; i < PnlHours.Controls.Count; i++)
            {
                switch (PnlHours.Controls[i])
                {
                    case CheckBox chk:
                        hours[chk.Tag.ToInt()] = chk.Checked ? "1" : "0";
                        break;
                }
            }
            for (int i = 0; i < hours.Length; i++)
            {
                HourOn += hours[i] == "1" ? "1" : "0";
            }
            myXML.SetAttrValue("HourOn", HourOn); 
            #endregion
            Itrycn_Db.SetSetting("Setting", myXML.XMLText);
            ryCommon.RyRegedit.RegRoot = Microsoft.Win32.RegistryHive.CurrentUser;
            ryCommon.RyRegedit.SetAutoRun(ChkAutoRun.Checked, Custom.AutoRunName, "\"" + Application.ExecutablePath.Replace("/","\\") + "\" "+ Custom.AutoRunPram);
            if (_RestTip_On != ChkRestTip_On.Checked || _RestInteval != NumRestInteval.Value || _Rest != NumRest.Value) //初始化休息数据
            {
                Itrycn_Info.ReadSetting();
            }
            else { Itrycn_Info.ReadSetting(false); }
            dr = DialogResult.OK;
            this.Close();
        }

        private void ChkAutoClose_CheckedChanged(object sender, EventArgs e)
        {
            NuAutoCloseMinute.Enabled = ChkAutoClose.Checked;
        }

        private void ChkHourlyChime_On_CheckedChanged(object sender, EventArgs e)
        {
            PnlHourlyChime.Enabled = ChkHourlyChime_On.Checked;
        }

        private void ChkRestTip_On_CheckedChanged(object sender, EventArgs e)
        {
            PnlRestTip.Enabled = ChkRestTip_On.Checked;
        }

        private void ChkDelayRest_CheckedChanged(object sender, EventArgs e)
        {
            NumDelayRestCount.Enabled = ChkDelayRestOn.Checked;
        }

        private void ChkStopRestByIdle_CheckedChanged(object sender, EventArgs e)
        {
            NumIdleMinute.Enabled= ChkStopRestByIdle.Checked;
        }

        private void BtnSpeak_Click(object sender, EventArgs e)
        {
            try
            {
                var spVoices = new COM.SpVoice()
                {
                    Rate =NumSpeakerRate.Value.ToInt(),
                    Volume = NumSpeakerVolume.Value.ToInt()
                };
                spVoices.SetVoices(CbbSpeaker.Text);
                spVoices.Speak("这是一个测试。This is a test", COM.SpVoice.Flags.SVSFlagsAsync);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ChkTipBeforeRest_CheckedChanged(object sender, EventArgs e)
        {
            ChkDelayRestOn.Enabled = ChkTipBeforeRest.Checked;
            NumDelayRestCount.Enabled = ChkTipBeforeRest.Checked;
        }

        private void ChkRestMusic_On_CheckedChanged(object sender, EventArgs e)
        {
            PnlRestMusic.Enabled = ChkRestMusic_On.Checked;
        }

        private void BtnBrowserMusic_Click(object sender, EventArgs e)
        {
            if(CbbMusicType.SelectedIndex == 0)
            {
               if(openFileDialog1.ShowDialog()==DialogResult.OK)
                {
                    CbbMusicPath.Text = openFileDialog1.FileName;
                }
            }
            else if (CbbMusicType.SelectedIndex == 1)
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    CbbMusicPath.Text = folderBrowserDialog1.SelectedPath;
                }
            }
        }
        private void Sound_OnPlayEnd(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                BtnTestMusic.Text = "测试"; 
            }));
        }
        API.SoundPlay sound = new API.SoundPlay();
        private void BtnTestMusic_Click(object sender, EventArgs e)
        {
            if (sound.PlaybackState == NAudio.Wave.PlaybackState.Playing)
            {
                sound.Stop();
            }
            else
            {
                BtnTestMusic.Text = "停止";
                sound.Volume = (float)NumMusicVolume.Value / 100f;
                sound.PlaySync(Itrycn_Info.SysDbFolder + "\\animation\\sound\\默认提醒.wav");
            }
        }

        private void FrmSetting_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (sound.PlaybackState == NAudio.Wave.PlaybackState.Playing)
            {
                sound.Stop();
            }
            while (BtnTestMusic.Text != "测试")
            {
                Application.DoEvents();
            }
        }

        private void NumRestOpacity_ValueChanged(object sender, EventArgs e)
        {
            Opacity = NumRestOpacity.Value.ToInt()/100d;
        }

        private void ChkIdleOver_On_CheckedChanged(object sender, EventArgs e)
        {
            NumIdleOverMinute.Enabled = ChkIdleOver_On.Checked;
        }
    }
}
