﻿/******************************************************************************
 プロジェクト: loxXmlUtils
 ライセンス: MIT License (http://opensource.org/licenses/mit-license.php)
   http://sourceforge.jp/projects/opensource/wiki/licenses%2FMIT_license
 *****************************************************************************/
/******************************************************************************
 Copyright (c) 2012-2015 synctam

 Permission is hereby granted, free of charge, to any person obtaining a copy of
 this software and associated documentation files (the "Software"), to deal in
 the Software without restriction, including without limitation the rights to
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 of the Software, and to permit persons to whom the Software is furnished to do
 so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *****************************************************************************/
//using Google.GData.Spreadsheets;
//using GoogleDocUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Uguu.IO.Csv;

namespace loxXmlUtils
{
    public class TJxDlg
    {
        private enum TNodeMode
        {
            None,
            Category1,
            Category2,
            Complex,
        }
        private TNodeMode FNodeMode = new TNodeMode();

        private enum TAttrMode
        {
            None,
            Text,
            speaker,
            Title
        }
        private TAttrMode FAttrMode = new TAttrMode();

        protected List<TJxDlgItems> FItemList = new List<TJxDlgItems>();
        public List<TJxDlgItems> ItemList { get { return this.FItemList; } }

        private List<TJxDlgTransCsv> FGoogleTransList = new List<TJxDlgTransCsv>();

        public TJxFlashCard FalshCard { get; set; }

        private TJxFlashCard.TConvertMode FConvertMode = TJxFlashCard.TConvertMode.ProperNounJapanese;
        public TJxFlashCard.TConvertMode ConvertMode { set { this.FConvertMode = value; } get { return this.FConvertMode; } }

        protected bool FisTranslate = false;

        private string FCategory1 = null;
        private string FCategory2 = null;
        private string FSpeaker = null;

        private TJxDlgItems FItem = null;

        protected XmlDocument FXmlDoc = new XmlDocument();

        /// <summary>
        /// Nodeが入れ子の時、旧Node情報を保存(push)し、Nodeを抜けるときに復帰(pop)する。
        /// </summary>
        private Stack<TNodeMode> FNodeModeStack = new Stack<TNodeMode>();
        /// <summary>
        /// Propertiesが入れ子の時、旧Properties情報を保存(push)し、Propertiesを抜けるときに復帰(pop)する。
        /// </summary>
        private Stack<TJxDlgItems> FItemStack = new Stack<TJxDlgItems>();

        public void loadFromXml(string FileName, Encoding encXML = null)
        {
            if (encXML == null) encXML = Encoding.GetEncoding("UTF-8");
            using (StreamReader fStream = new StreamReader(FileName, encXML)) {
                this.FXmlDoc.Load(fStream);
            }
            this.FNodeMode = TNodeMode.None;
            XmlElement elem = this.FXmlDoc.DocumentElement;
            if (elem.HasChildNodes == true) {
                XmlNode childNode = elem.FirstChild;
                readNode(childNode);
            }

            Console.WriteLine("loadFromXml {0}", this.FItemList.Count);
        }

        /// <summary>
        /// XMLのノードを読み日本語化情報を抽出する。子ノードがある場合は再帰的に処理する。
        /// </summary>
        /// <param name="node">ノード</param>
        protected void readNode(XmlNode node)
        {
            TNodeMode wNodeMode = TNodeMode.None;

            // Nodeに入った時の処理
            switch (node.Name.ToLower()) {
                case "dictionary":
                    wNodeMode = onEnterDictonaryNode(node, wNodeMode);
                    break;
                case "complex":
                    wNodeMode = onEnterComplexNode(node, wNodeMode);
                    break;
                case "simple":
                    onEnterSimpleNode(node);
                    break;
                default:
                    break;
            }

            // 子ノードがあればそれを処理
            if (node.HasChildNodes) {
                foreach (XmlNode nodeData in node.ChildNodes) {
                    FNodeModeStack.Push(this.FNodeMode); // Node情報を保存
                    readNode(nodeData); // 再帰で子ノードの処理
                    this.FNodeMode = FNodeModeStack.Pop(); // Node情報を復帰
                }
            }

            // ノードを抜けた時の処理
            if (wNodeMode == this.FNodeMode) {
                switch (wNodeMode) {
                    case TNodeMode.None:
                        // skip
                        break;
                    case TNodeMode.Category1:
                        // onLeaveCategory1
                        //Console.WriteLine("leave({0})", wNodeMode);
                        break;
                    case TNodeMode.Category2:
                        // onLeaveCategory2
                        //Console.WriteLine("leave({0})", wNodeMode);
                        break;
                    case TNodeMode.Complex:
                        // onLeaveComplex
                        if ((this.FItem != null) && (this.FItem.Text != null)) {
                            this.FItem.Category1 = this.FCategory1;
                            this.FItem.Category2 = this.FCategory2;
                            this.FItem.Speaker = this.FSpeaker;
                            this.FItemList.Add(this.FItem);
                            this.FSpeaker = ""; // v.1.3 初期化漏れ対応
                        }
                        // 旧Item情報を復帰する
                        this.FItem = this.FItemStack.Pop();
                        break;
                    default:
                        throw new Exception("unknown TNodeMode");
                }
            }
        }

        private void onEnterSimpleNode(XmlNode node)
        {
            if (this.FNodeMode == TNodeMode.Category1) {
                // onChangeCategory1
                if (node.Attributes.Count == 1) {
                    this.FCategory1 = node.Attributes[0].Value;
                }
            } else if (this.FNodeMode == TNodeMode.Category2) {
                // onChangeCategory2
                if (node.Attributes.Count == 1) {
                    this.FCategory2 = node.Attributes[0].Value;
                }
            } else if (this.FNodeMode == TNodeMode.Complex) {
                // onDetail
                if (this.FItem != null) {
                    string Value = null;
                    foreach (XmlAttribute attr in node.Attributes) {
                        switch (attr.Name.ToLower()) {
                            case "name":
                                switch (attr.Value.ToLower()) {
                                    case "speaker":
                                        FAttrMode = TAttrMode.speaker;
                                        break;
                                    case "text":
                                        FAttrMode = TAttrMode.Text;
                                        break;
                                    case "title":
                                        FAttrMode = TAttrMode.Title;
                                        break;
                                    default:
                                        FAttrMode = TAttrMode.None;
                                        break;
                                }
                                break;
                            case "value":
                                Value = TJxCommon.EscapeControlChar(attr.Value);
                                // ここでattrを更新し日本語化する
                                // 更新はAttrのInnerTextを使用する
                                if ((this.FisTranslate) && ((FAttrMode == TAttrMode.Text)||(FAttrMode == TAttrMode.Title))) {
                                    attr.InnerText = TranslateE2J(attr.Value, this.FConvertMode); // 固有名詞日本語版@@@@
                                    //Console.WriteLine(node.InnerText);
                                    //Console.WriteLine(data.InnerText);
                                }
                                break;
                            default:
                                break;
                        }
                        switch (this.FAttrMode) {
                            case TAttrMode.speaker:
                                this.FSpeaker = Value;
                                break;
                            case TAttrMode.Text:
                                this.FItem.Text = TJxCommon.EscapeControlChar(Value);
                                break;
                            case TAttrMode.Title:
                                if ((Value != null) && (Value != "")) {
                                    this.FSpeaker = "@@TITLE@@";
                                    this.FItem.Text = TJxCommon.EscapeControlChar(Value);
                                }
                                break;
                            case TAttrMode.None:
                                break;
                            default:
                                throw new Exception("unknown attr mode");
                        }
                    }
                }
            }
        }

        private TNodeMode onEnterComplexNode(XmlNode node, TNodeMode wNodeMode)
        {
            // onEnterComplex
            wNodeMode = TNodeMode.Complex;
            this.FNodeMode = wNodeMode;
            // 旧Item情報を保存する
            this.FItemStack.Push(this.FItem);

            if (node.Attributes.Count == 1) {
                if (node.Attributes[0].Value == "JX.JXDialog+Entry_Narrator, JXEngine") {
                    this.FSpeaker = "Narrator";
                } else if (node.Attributes[0].Value == "JX.JXDialog+Entry_Dialog, JXEngine") {
                    this.FSpeaker = null;
                } else {
                    // skip
                }
            }
            this.FItem = new TJxDlgItems();
            return wNodeMode;
        }

        private TNodeMode onEnterDictonaryNode(XmlNode node, TNodeMode wNodeMode)
        {
            foreach (XmlAttribute attr in node.Attributes) {
                if (attr.Value == "Categories") {
                    // onEnterCategory1
                    wNodeMode = TNodeMode.Category1;
                    this.FNodeMode = wNodeMode;
                } else if (node.Attributes.Count == 2) {
                    // onEnterCategory2
                    wNodeMode = TNodeMode.Category2;
                    this.FNodeMode = wNodeMode;
                }
            }
            return wNodeMode;
        }

        private string TranslateE2J(string English, TJxFlashCard.TConvertMode ConvertMode)
        {
            // @@@@@@@@@@@@@@@@ 日本語化ロジックを追加すること
            string result = English;
            foreach (TJxDlgTransCsv data in this.FGoogleTransList) {
                if (TJxCommon.unEscapeControlChar(data.English.Replace("'", "").Replace(" ", "")) == English.Replace("'", "").Replace(" ", "")) {
                    result = data.Japanese;
                    result = this.FalshCard.Convert(result, ConvertMode);
                    break;
                }
            }
            result = TJxCommon.unEscapeControlChar(result);
            return result;
        }
        //*********************************************************************************************************
        public override string ToString()
        {
            StringBuilder result = new StringBuilder(2048);
            foreach (TJxDlgItems data in this.FItemList) {
                result.Append(data.ToString());
                result.Append("\r\n");
            }
            return result.ToString();
        }
        //*********************************************************************************************************
        public List<Dictionary<string, string>> ToDictionary()
        {
            List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
            foreach (TJxDlgItems data in this.FItemList) {
                Dictionary<string, string> dict = data.ToDictionary();
                result.Add(dict);
            }
            return result;
        }
        //*********************************************************************************************************
        public void saveToXml(string FileName)
        {
            this.FNodeMode = TNodeMode.None;
            this.FisTranslate = true;
            this.FItemList.Clear(); // v.1.3 初期化漏れ
            XmlElement elem = this.FXmlDoc.DocumentElement;
            if (elem.HasChildNodes == true) {
                XmlNode childNode = elem.FirstChild;
                readNode(childNode);
            }




            this.FXmlDoc.Save(FileName);
        }
        //*********************************************************************************************************
        /// <summary>
        /// XMLから作成したリストをCSVファイルに出力する。
        /// </summary>
        /// <param name="FileName"></param>
        public void saveToCsv(string FileName)
        {
            using (StreamWriter writer = new StreamWriter(FileName, false, Encoding.UTF8)) {
                using (CsvWriter csv = new CsvWriter(writer)) {
                    csv.Write("[[Sequence]]");
                    csv.Write("[[Category1]]");
                    csv.Write("[[Category2]]");
                    csv.Write("[[Speaker]]");
                    csv.Write("[[Text]]");
                    csv.WriteNewLine();
                    int no = 0;
                    foreach (TJxDlgItems data in this.FItemList) {
                        no++;
                        csv.Write(no.ToString());
                        Dictionary<string, string> dict = data.ToDictionary();
                        foreach (KeyValuePair<string, string> pair in dict) {
                            csv.Write(pair.Value);
                        }
                        csv.WriteNewLine();
                    }
                }
            }
        }

        //*********************************************************************************************************
        internal class TJxDlgTransCsv
        {
            public int Seq { get; set; }
            public string Category1 { get; set; }
            public string Category2 { get; set; }
            public string Speaker { get; set; }
            public string English { get; set; }
            public string Japanese { get; set; }
            public string GoogleTrans { get; set; }
            public string Memo { get; set; }
            public string MemoAdmin { get; set; }
        }
        /// <summary>
        /// Googleの翻訳シートを読み込み翻訳リストを作成する
        /// </summary>
        /// <param name="FileName">翻訳シートのファイル名</param>
        /// <param name="encCSV">文字コード</param>
        internal void makeGoogleTransCsvList(string FileName, Encoding encCSV = null)
        {
            if (encCSV == null) encCSV = Encoding.UTF8;
            using (StreamReader reader = new StreamReader(FileName, encCSV)) {
                using (CsvReader csvReader = new CsvReader(reader, "\n", ",", false)) {
                    this.FGoogleTransList.Clear();
                    while (csvReader.Read()) {
                        if (csvReader[0].StartsWith("[[")) {
                            // 1行目は見出し行なのでスキップ
                        } else {
                            TJxDlgTransCsv data = new TJxDlgTransCsv();
                            data.Seq = int.Parse(csvReader[0]);
                            data.Category1 = csvReader[1];
                            data.Category2 = csvReader[2];
                            data.Speaker = csvReader[3];
                            data.English = csvReader[4];
                            data.Japanese = csvReader[5];
                            data.GoogleTrans = csvReader[6];
                            data.Memo = csvReader[7];
                            data.MemoAdmin = csvReader[8];
                            if ((data.Japanese != "") && (data.Japanese != null)) { // 翻訳済みデータのみ登録
                                this.FGoogleTransList.Add(data);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Googleの翻訳シートをネット経由で読み込み翻訳リストを作成する
        /// </summary>
        //internal void makeGoogleTransList(string appName, string user, string ClientID, string ClientSecret, string BookName, string SheetName = null)
        //{
        //    if (string.IsNullOrWhiteSpace(BookName)) {
        //        BookName = TJxCommon.BOOK_NAME;
        //    }
        //    if (string.IsNullOrWhiteSpace(SheetName)) {
        //        SheetName = "SOL_EN.jxdlg";
        //    }
        //    this.FGoogleTransList.Clear();
        //    try {
        //        JxGoogleSpreadsheet ggl = new JxGoogleSpreadsheet();
        //        ListFeed sheet = ggl.getTablebyBookAndSheet(appName, user, ClientID, ClientSecret, BookName, SheetName);
        //        foreach (ListEntry row in sheet.Entries) {
        //            TJxDlgTransCsv data = new TJxDlgTransCsv();
        //            data.Seq = int.Parse(row.Elements[0].Value);
        //            data.Category1 = row.Elements[1].Value;
        //            data.Category2 = row.Elements[2].Value;
        //            data.Speaker = row.Elements[3].Value;
        //            data.English = row.Elements[4].Value;
        //            data.Japanese = row.Elements[5].Value;
        //            data.GoogleTrans = row.Elements[6].Value;
        //            data.Memo = row.Elements[7].Value;
        //            data.MemoAdmin = row.Elements[8].Value;
        //            //item.Dummy = row.Elements[9].Value;
        //            if (!string.IsNullOrWhiteSpace(data.Japanese)) {
        //                // 翻訳済みデータのみ登録
        //                this.FGoogleTransList.Add(data);
        //            }
        //        }
        //        Console.WriteLine("Googleスプレッドシート処理件数({0})：{1}", SheetName, this.FGoogleTransList.Count);
        //    }
        //    catch (ArgumentException ex) {
        //        Console.Error.WriteLine(ex.StackTrace);
        //        Console.Error.WriteLine(ex.Message);
        //        throw;
        //    }
        //}
        /// <summary>
        /// XMLから作成したリストにGoogle翻訳リストを反映し、CSVファイルに出力する。翻訳ファイルの確認用に使用。事前に「makeGoogleTransList」で翻訳リストを作成しておくこと。
        /// </summary>
        /// <param name="FileNameOut">出力するCSVファイル名</param>
        /// <param name="encCSV">CSVファイルの文字コード</param>
        internal void checkTrans(string FileNameOut, Encoding encCSV = null)
        {
            if (encCSV == null) encCSV = Encoding.UTF8;
            List<TJxDlgTransCsv> csvOutList = new List<TJxDlgTransCsv>();
            int seq = 0;
            foreach (TJxDlgItems item in this.FItemList) {
                TJxDlgTransCsv outItem = new TJxDlgTransCsv();
                outItem.Category1 = item.Category1;
                outItem.Category2 = item.Category2;
                outItem.Speaker = item.Speaker;
                outItem.English = item.Text;
                outItem.GoogleTrans = "";
                outItem.Japanese = "";
                outItem.Memo = "";
                outItem.MemoAdmin = "";
                seq++;
                outItem.Seq = seq;
                outItem.Speaker = item.Speaker;
                foreach (TJxDlgTransCsv trans in FGoogleTransList) {
                    if (outItem.English == trans.English) {
                        outItem.GoogleTrans = trans.GoogleTrans;
                        outItem.Japanese = trans.Japanese;
                        outItem.Memo = trans.Memo;
                        outItem.MemoAdmin = trans.MemoAdmin;
                        break;
                    }
                }
                csvOutList.Add(outItem);
            }

            using (StreamWriter writer = new StreamWriter(FileNameOut, false, encCSV)) {
                using (CsvWriter csv = new CsvWriter(writer)) {
                    //csv.Write("[[FileName]]");
                    csv.Write("[[Seq]]");
                    csv.Write("[[Category1]]");
                    csv.Write("[[Category2]]");
                    csv.Write("[[Speaker]]");
                    csv.Write("[[English]]");
                    csv.Write("[[Japanese]]");
                    csv.Write("[[Google翻訳]]");
                    csv.Write("[[メモ]]");
                    csv.Write("[[管理用メモ]]");
                    csv.WriteNewLine();
                    foreach (TJxDlgTransCsv data in csvOutList) {
                        //csv.Write(data.FileName);
                        csv.Write(data.Seq.ToString());
                        csv.Write(data.Category1);
                        csv.Write(data.Category2);
                        csv.Write(data.Speaker);
                        csv.Write(data.English);
                        csv.Write(data.Japanese);
                        csv.Write(data.GoogleTrans);
                        csv.Write(data.Memo);
                        csv.Write(data.MemoAdmin);
                        csv.WriteNewLine();
                    }
                }
            }
        }
        //*********************************************************************************************************
    }
}
