using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
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;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// DictionaryEditor.xaml 的交互逻辑
    /// </summary>
    public partial class DictionaryEditor : MetroWindow
    {
        /// <summary>
        /// [构造方法]创建一个词典编辑器。
        /// </summary>
        /// <param name="dictionaryFilePath"></param>
        public DictionaryEditor(string dictionaryFilePath)
        {
            InitializeComponent();

            this.dictionaryFilePath = dictionaryFilePath;

            if (File.Exists(dictionaryFilePath) == false) throw new FileNotFoundException($"文件“{dictionaryFilePath}”不存在。");

            using (StreamReader sr = new StreamReader(dictionaryFilePath))
            {
                char[] splitter = new char[] { '\t' };
                var lineText = sr.ReadLine();
                ObservableCollection<EnToChEntry> dictionaryEntries = new ObservableCollection<EnToChEntry>();

                while (lineText != null)
                {
                    if (lineText.StartsWith(";") || lineText.StartsWith(";"))
                    {
                        lineText = sr.ReadLine();
                        continue;
                    }

                    var spans = lineText.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

                    EnToChEntry ece = new EnToChEntry();

                    var i = 0;
                    if (i < spans.Length) ece.English = spans[i];
                    i++;
                    if (i < spans.Length) ece.Chinese = spans[i];
                    i++;
                    if (i < spans.Length) ece.Alpha = spans[i];
                    i++;
                    if (i < spans.Length) ece.Comment = spans[i];

                    dictionaryEntries.Add(ece);
                    lineText = sr.ReadLine();
                }

                dg.DataContext = dictionaryEntries;
            }
        }

        private string dictionaryFilePath;
        /// <summary>
        /// 词典文件路径。
        /// </summary>
        public string DictionaryFilePath
        {
            get { return dictionaryFilePath; }
        }

        /// <summary>
        /// 放弃编辑结果,关闭窗口。
        /// </summary>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        /// <summary>
        /// 保存编辑的结果。
        /// </summary>
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                foreach (var row in dg.DataContext as ObservableCollection<EnToChEntry>)
                {
                    sb.Append(row.English);
                    sb.Append("\t");
                    sb.Append(row.Chinese);
                    sb.Append("\t");
                    sb.Append(row.Alpha);
                    sb.Append("\t");
                    sb.Append(row.Comment);
                    sb.Append("\r\n");
                }

                using (StreamWriter sw = new StreamWriter(this.DictionaryFilePath))
                {
                    sw.Write(sb.ToString());
                }
                this.DialogResult = true;
            }
            catch (Exception ex)
            {
                this.DialogResult = false;
                LMessageBox.Show(ex.Message, Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                this.Close();
            }
        }

        /// <summary>
        /// 使行标头都加上前缀文本,好看点。
        /// </summary>
        private void dg_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = ">>";
        }

        /// <summary>
        /// 显示状态栏信息。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (e.AddedCells.Count <= 0)
            {
                tbStatus.Text = $"共 {dg.Items.Count} 行。";
                return;
            }

            tbStatus.Text = $"第 {dg.Items.IndexOf(e.AddedCells[0].Item) + 1} 行,共 {dg.Items.Count} 行。";
        }
    }
}