using desktopEnglish.entity;
using desktopEnglish.utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Text;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace desktopEnglish
{
    public partial class Form1 : Form
    {
        //保存文件中读取的单词
        private List<string> wordList = new List<string>();
        //保存获取后的单词解释、读音
        private List<Word> wordStoreList = new List<Word>();
        //计数器
        int index = 0;
        //背景窗体
        BackForm backForm;
        //单词
        StringBuilder wordStrBuilder = new StringBuilder();
        //常规设置
        public static RoutineSetting routineSetting;
        //单词设置
        public static WordSetting wordSetting;
        //时间控制器
        public static Timer timerStaRandom;
        //单词
        public static Word word = new Word();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //窗口置顶
            this.TopMost = true;

            wordSetting = UtilSerialize.DeserializeFromFile(FinalStrPath.WordConfigPath) as WordSetting;
            if(wordSetting == null)
            {
                wordList.Add("sky");
            }
            else
            {
                wordList = ReadWord.getAllWord(wordSetting.WordDirectoryPath + "//" + wordSetting.WordFileName);
            }

            routineSetting = UtilSerialize.DeserializeFromFile(FinalStrPath.RoutineConfigPath) as RoutineSetting;
            if(routineSetting == null)
            {
                routineSetting = RoutineSetting.initRoutineSetting();
            }
            this.timerRandom.Interval = routineSetting.Speed * 1000;
            // 设置背景全透明
            this.BackColor = Color.AliceBlue;
            this.TransparencyKey = Color.AliceBlue;
            // 设置窗体鼠标穿透
            SetPenetrate();

            backForm = new BackForm(this, routineSetting.BackColor, routineSetting.Opacity);
            backForm.flushForm += BackForm_flushForm;
            backForm.Show();
            this.SaveWords(sender, e);
            timerStaRandom = this.timerRandom;
        }
        //设置改变后，窗体字体刷新
        private void BackForm_flushForm()
        {
            //关闭设置窗体后，重新读取单词列表
            wordList = ReadWord.getAllWord(wordSetting.WordDirectoryPath + "//" + wordSetting.WordFileName);
            //清空单词缓存列表
            wordStoreList.Clear();
            //重置下标
            this.index = 0;
            //重新获取单词显示
            this.SaveWords(null, null);
        }

        #region win32 api
        private const uint WS_EX_LAYERED = 0x80000;
        private const int WS_EX_TRANSPARENT = 0x20;
        private const int GWL_STYLE = (-16);
        private const int GWL_EXSTYLE = (-20);
        private const int LWA_ALPHA = 0;

        [DllImport("user32", EntryPoint = "SetWindowLong")]
        private static extern uint SetWindowLong(
            IntPtr hwnd,
            int nIndex,
            uint dwNewLong
        );

        [DllImport("user32", EntryPoint = "GetWindowLong")]
        private static extern uint GetWindowLong(
            IntPtr hwnd,
            int nIndex
        );

        [DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]
        private static extern int SetLayeredWindowAttributes(
            IntPtr hwnd,
            int crKey,
            int bAlpha,
            int dwFlags
        );
        #endregion

        /// <summary> 
        /// 设置窗体具有鼠标穿透效果 
        /// </summary> 
        public void SetPenetrate()
        {
            GetWindowLong(this.Handle, GWL_EXSTYLE);
            SetWindowLong(this.Handle, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED);
        }


        /// <summary>
        /// 让程序不显示在alt+Tab视图窗体中
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_EX_APPWINDOW = 0x40000;
                const int WS_EX_TOOLWINDOW = 0x80;
                CreateParams cp = base.CreateParams;
                cp.ExStyle &= (~WS_EX_APPWINDOW);    // 不显示在TaskBar
                cp.ExStyle |= WS_EX_TOOLWINDOW;      // 不显示在Alt+Tab
                return cp;
            }
        }

        /// <summary>
        ///  设置定时任务
        /// </summary>
        private void timerRandom_Tick(object sender, EventArgs e)
        {
            this.SaveWords(sender, e);
        }

        /// <summary>
        /// 集合中填充单词
        /// </summary>
        private void SaveWords(object sender, EventArgs e)
        {
            if (this.wordStoreList.Count == this.wordList.Count)
            {
                // 从缓存集合中取出单词
                Random r = new Random();
                int storeIndex = r.Next(0, this.wordStoreList.Count);
                word = this.wordStoreList[storeIndex];
            }
            //wordDict还没有填满
            if (index < this.wordList.Count)
            {
                word = BiYingDict.getInfo(this.wordList[this.index]);
                this.wordStoreList.Add(word);
                index++;
            }
            this.wordStrBuilder.Clear();
            this.wordStrBuilder.Append(this.FormatWord(word));
            this.Form1_Paint(sender, e as PaintEventArgs);
        }



        /// <summary>
        ///    输出单词格式处理
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private string FormatWord(Word word)
        {
            if (word == null)
            {
                return "";
            }
            string str = "";
            str += word.KeyWord + "\n";
            string[] explainArray = word.Explain.Split("，");
            if (explainArray.Length > 2)
            {
                //拼接中英文读音
                str += explainArray[0] + "， " + explainArray[1].Replace(";", "");
                string[] explainArray2 = Regex.Split(explainArray[2], "；");
                foreach (string s in explainArray2)
                {
                    if (s == " ")
                    {
                        continue;
                    }
                    // 如果此项中能匹配到英文
                    if (Regex.IsMatch(s, "[a-z]+"))
                    {
                        str += "；\n" + s;
                        continue;
                    }
                    str += s + "，";
                }
            }
            string newStr = str.Substring(0, str.Length - 1) + "；";
            return newStr.Trim().Replace(" ", "");
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (this.wordStrBuilder.Length == 0)
            {
                return;
            }
            Font font = routineSetting.Font;
            Size size = TextRenderer.MeasureText(wordStrBuilder.ToString(), font);
            Size newSize = new Size(Convert.ToInt32(size.Width * 1.1), Convert.ToInt32(size.Height * 1.4));
            this.Size = newSize;
            this.backForm.Size = newSize;
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
            g.DrawString(wordStrBuilder.ToString(), font, new SolidBrush(routineSetting.FontColor), new PointF(30, 20));
            g.Dispose();
        }

        // 窗体关闭时，停止timer
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.timerRandom.Stop();
        }

    }
}
