using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace カブラウザもどき
{
    class Utils
    {
        /**
         * className に該当する、最初に見つかった要素を返す
         */
        public static HtmlElement GetElementByClassName(HtmlElement elm, string className)
        {
            HtmlElement target = null;
            foreach (HtmlElement e in elm.All) {
                if (e.GetAttribute("className") == className) {
                    target = e;
                    break;
                }
            }
            return target;
        }
        /**
         * className に該当する、最初に見つかった要素を返す
         */
        public static HtmlElement GetElementByClassName(HtmlElement elm, string className, string tagName)
        {
            HtmlElement target = null;
            HtmlElementCollection childs = elm.GetElementsByTagName(tagName);
            foreach (HtmlElement e in childs) {
                if (e.GetAttribute("className") == className) {
                    target = e;
                    break;
                }
            }
            return target;
        }

        /**
         * className に該当する、iCount番目のHTML要素を返す
         */
        public static HtmlElement GetElementByClassName(HtmlDocument doc, string className, string tagName, int iCount)
        {
            int i = 0;
            HtmlElement target = null;
            HtmlElementCollection elms = doc.GetElementsByTagName(tagName);
            foreach (HtmlElement e in elms) {
                if (e.GetAttribute("className") == className) {
                    i++;
                    if (i == iCount) {
                        target = e;
                        break;
                    }
                }
            }
            return target;
        }

        /**
         * innerTextにtxtを持つ、最初のHTML要素を返す
         */
        public static HtmlElement GetElementByText(HtmlElement elm, string txt, string tagName)
        {
            int i = 0;
            HtmlElement target = null;
            HtmlElementCollection elms = elm.GetElementsByTagName(tagName);
            foreach (HtmlElement e in elms) {
                if (e.InnerText != null && e.InnerText.IndexOf(txt) > 0) {
                    target = e;
                    break;
                }
            }
            return target;
        }

        /**
         * 「投稿時の気持ち」を持つTD Elemntを戻す
         */
        public static HtmlElement GetEmotionElement(HtmlElement elm)
        {
            int i = 0;
            HtmlElement target = null;
            HtmlElementCollection elms = elm.GetElementsByTagName("TD");
            foreach (HtmlElement e in elms) {
                if (e.InnerText != null && e.InnerText.IndexOf("投稿時の気持ち: ") > 0) {
                    if (e.GetAttribute("align") == "left") {
                        target = e;
                        break;
                    }
                }
            }
            return target;
        }
        /// <summary>
        /// 以下のような文字列を、日付、最大MID、MIDの配列にして戻す
        /// 2004/ 3/ 1 12:44 [ No.1734 / 20232 ]
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string[] ParseTile(string src)
        {
            string[] target = new String[3];
            Regex reg = new System.Text.RegularExpressions.Regex("[1-2][0-9]{3}/( |[0-9])[0-9]/( |[0-9])[0-9] ( |[0-9])( |[0-9])?:( |[0-9])( |[0-9])?");
            MatchCollection match = reg.Matches(src);
            if (match.Count == 0) {
                return null;
            } else {
                string maxTitleNo = src.Split('[')[1].Split('/')[1].Replace("]", "").TrimEnd().TrimStart();
                string titleNo = src.Split('[')[1].Split('/')[0].Replace("No.", "").TrimEnd().TrimStart();
                string sendTime = src.Split('[')[0].TrimStart().TrimEnd();
                target[0] = sendTime;
                target[1] = maxTitleNo;
                target[2] = titleNo;
            }
            return target;
        }

        /// <summary>
        /// xxxx.datファイルを重複を除いて、降順にソートする
        /// </summary>
        /// <param name="path"></param>
        public static void SortUniqTitleList(string path)
        {

            IDictionary dic = new Dictionary<int, string>();
            List<KeyValuePair<int, string>> list;
            // 保存したメッセージ一覧をsort & uniqする
            using (StreamReader sr = new StreamReader(path)) {
                StringReader tmp = new StringReader(sr.ReadToEnd());

                string[] splittedline;
                sr.Close();
                string line;
                while ((line = tmp.ReadLine()) != null) {
                    splittedline = line.Split(Form1.delimiter);
                    dic[int.Parse(splittedline[0])] = line;
                }

                list = SortByKey((Dictionary<int, string>)dic);

                StreamWriter sw = new StreamWriter(path);
                sw.Write("");
                foreach (KeyValuePair<int, string> tmpLine in list) {
                    sw.WriteLine(tmpLine.Value);
                }
                sw.Close();
                return;
            }
        }

        /// <summary>
        /// 連想配列のリストをキーでソートする
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static List<KeyValuePair<int, string>> SortByKey(Dictionary<int, string> dic)
        {
            List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>(dic);
            list.Sort(
              delegate(KeyValuePair<int, string> kvp1, KeyValuePair<int, string> kvp2)
              {
                  return kvp2.Key - kvp1.Key;
              });
            return list;
        }
    }
}
