//ライセンス情報はAgeOnフォルダのLISENCEフォルダを参照してください
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using mshtml;
using System.Windows.Forms;
using System.Threading;
using System.IO;

using nispi.controlclass;

namespace nispi.WriteToBoard
{
    class PostData
    {
        public WriteData writeData;
        public WriteMain writeMain;
        public string nowTime;

        public PostData(WriteMain writeMain, WriteData writeData)
        {
            this.writeMain = writeMain;
            this.writeData = writeData;
        }

        public void Start()
        {
            if (this.writeData.contentsText.Length == 0) return;

            Thread t = new Thread(new ThreadStart(PostDataTask));
            t.IsBackground = true;
            t.Start();
        }

        private void PostDataTask()
        {
            //this.writeData = writeData;

            //if (this.writeData.contentsText.Length == 0) return;
            nowTime = (UnixTime.GetNowUnixTime(DateTime.UtcNow) - 10000).ToString().Split('.')[0];

            this.writeData.postData = MakePostData(
                this.writeData.nameText, this.writeData.mailText, this.writeData.contentsText,
                nowTime, this.writeData.buttonText);

            this.writeData.postData = nispi.WriteToThread.PostData.AddHiddenValue(this.writeData.postData, this.writeData.boardUrl);
            
            string resData = PostTo2ch(this.writeData.postData);

            //しずちゃん用。
            if (this.writeData.boardUrl.Contains("shizu.0000.jp") == true)
            {
                Const.form.mainForm.Invoke((Action)(() => this.writeData.htmlData = "<html><body>書き込みました<body></html>"));

                this.writeMain.MODE = "BROWSER";
                WriteToBrowser();
                //ログに出力
                this.SaveLog();
                this.writeMain.ChangePanel("書き込みました");
                return;
            }

            this.writeMain.writeBrowserPanel.innerBrowserParts.BrowserClear();

            string title = "";
            string text = "";

            Const.form.mainForm.Invoke((Action)(() => this.writeMain.writeBrowserPanel.innerBrowserParts.Write(resData)));
            //this.writeMain.writeBrowserPanel.innerBrowserParts.Write(resData);
            Const.form.mainForm.Invoke((Action)(() => this.writeMain.writeBrowserPanel.innerBrowserParts.AllowNavigation = false));

            Const.form.mainForm.Invoke((Action)(() => title = this.writeMain.writeBrowserPanel.innerBrowserParts.control.Document.Title));
            Const.form.mainForm.Invoke((Action)(() => text = this.writeMain.writeBrowserPanel.innerBrowserParts.control.Document.Body.InnerText));

            //フォームのアクションを書き換える

            if (true == title.Contains("書きこみました"))
            {
                Const.form.mainForm.Invoke((Action)(() => this.writeData.htmlData = "<html><body>書き込みました<body></html>"));

                this.writeMain.MODE = "BROWSER";
                WriteToBrowser();
                //ログに出力
                this.SaveLog();
                this.writeMain.ChangePanel("書き込みました");
            }
                
            else if ((true == title.Contains("ＥＲＲＯＲ")) || (true == title.Contains("お茶でも")))
            {
                Const.form.mainForm.Invoke((Action)(() => this.writeData.htmlData = this.writeMain.writeBrowserPanel.innerBrowserParts.control.Document.Body.OuterHtml));//"<html><body>書き込みました<body></html>";

                this.writeMain.MODE = "BROWSER";
                WriteToBrowser();
                this.writeMain.ChangePanel("");
            }

            else if (true == title.Contains("書き込み確認"))
            {
                HtmlElementCollection htmlElementCollection = null;

                Const.form.mainForm.Invoke((Action)(() => htmlElementCollection = this.writeMain.writeBrowserPanel.innerBrowserParts.control.Document.Forms));

                HtmlElementCollection htmlElementCollection2 = htmlElementCollection[0].Children;

                foreach (HtmlElement htmlElement in htmlElementCollection2)
                {
                    mshtml.IHTMLElement inputTag = (mshtml.IHTMLElement)htmlElement.DomElement;

                    mshtml.IHTMLInputElement iihl = inputTag as mshtml.IHTMLInputElement;
                    if (iihl == null) continue;

                    if ((false == iihl.name.Equals("subject")) &&
                        (false == iihl.name.Equals("FROM")) &&
                        (false == iihl.name.Equals("mail")) &&
                        (false == iihl.name.Equals("MESSAGE")) &&
                        (false == iihl.name.Equals("bbs")) &&
                        (false == iihl.name.Equals("time")) &&
                        (false == iihl.name.Equals("key")) &&
                        (true == iihl.type.Equals("hidden")))
                    {
                        string hiddenName = iihl.name;
                        string hiddenValue = iihl.value;

                        if (hiddenName == null) hiddenName = "test";
                        if (hiddenValue == null) hiddenValue = "test";

                        nispi.WriteToThread.PostData.SetHiddenValue(hiddenName, hiddenValue, this.writeData.boardUrl);

                        if (Util.BoardType(writeData.boardUrl) == Util.TYPE_NEXT2CH)
                            this.writeData.buttonText = "規約に同意して書き込む";
                        else
                            this.writeData.buttonText = "上記全てを承諾して書き込む";
                    }
                }
                string actionAddr = ((mshtml.HTMLFormElement)(htmlElementCollection[0].DomElement)).action;
                Const.form.mainForm.Invoke((Action)(() => ((mshtml.HTMLFormElement)(htmlElementCollection[0].DomElement)).action = "javascript:void(0);#kakunin" + "#" + actionAddr));
                Const.form.mainForm.Invoke((Action)(() => this.writeData.htmlData = this.writeMain.writeBrowserPanel.innerBrowserParts.control.Document.Body.OuterHtml));
                
                this.writeMain.MODE = "BROWSER";
                WriteToBrowser();
                this.writeMain.ChangePanel("");
            }
            else
            {
                Const.form.mainForm.Invoke((Action)(() => this.writeData.htmlData = this.writeMain.writeBrowserPanel.innerBrowserParts.control.Document.Body.OuterHtml));//"<html><body>書き込みました<body></html>";

                this.writeMain.MODE = "BROWSER";
                WriteToBrowser();
                this.writeMain.ChangePanel("");
            }
        }

        public string MakePostData(string name, string mail, string body, string server_time, string buttonText)
        {

            if (Util.BoardUrlToBoardTypeName(this.writeData.boardUrl).StartsWith("jbbs") == true)
            {
                this.writeData.postData = Util.BuildJbbsBoardPostStr(this.writeData.threadName,
                    name, mail, body, this.writeData.boardID, this.writeData.boardID, server_time);
            }
            if (Util.BoardUrlToBoardTypeName(this.writeData.boardUrl).StartsWith("machi") == true)
            {
                this.writeData.postData = Util.BuildMACHIBBSBoardPostStr(this.writeData.threadName,
                    name, mail, body, this.writeData.boardID, this.writeData.boardID, server_time);
            }
            else
            {
                this.writeData.postData = Util.BuildPostBoardStr(this.writeData.threadName, name, mail, body,
                    this.writeData.boardID, server_time, buttonText);

                if (Util.BoardType(this.writeData.boardUrl) == Util.TYPE_2CH)
                {
                    //浪人が有効ならば
                    if (Const.RoninState == true)
                        this.writeData.postData += "&sid=" + Const.RoninSessionID;
                }
            }
            return this.writeData.postData;
        }

        public string PostTo2ch(string postData)
        {

            nispi.WriteToThread.SendPostData sendPostData = new nispi.WriteToThread.SendPostData();
            if (true == sendPostData.Send(this.writeData.boardUrl, this.writeData.writeAddress, postData))
            {
                return sendPostData.httpResData;
            }
            else
            {
            }
            return "";
        }

        public void WriteToBrowser()
        {
            Const.form.mainForm.Invoke((Action)(() => this.writeMain.writeBrowserPanel.innerBrowserParts.BrowserClear()));
            Const.form.mainForm.Invoke((Action)(() => this.writeMain.writeBrowserPanel.myWebBrowserParts.BrowserClear()));

            Const.form.mainForm.Invoke((Action)(() => this.writeMain.writeBrowserPanel.myWebBrowserParts.Write(this.writeData.htmlData)));
            Const.form.mainForm.Invoke((Action)(() => this.writeMain.writeBrowserPanel.myWebBrowserParts.AllowNavigation = false));
        }

        //public WriteData GetWriteData(WriteData writeData)
        //{
        //    return this.writeData;
        //}
        public void SaveLog()
        {
            //ファイル名を板名とタイトル名と時間によって作る
            string fileName = BoardDataBase.GetName(
                this.writeData.boardUrl) + "." + this.writeData.threadName + "." + this.nowTime + ".txt";
            
            //名前：メール：内容のフォーマットでセーブする
            string str = "名前:" + this.writeData.nameText + "\r\n" +
                "メールアドレス:" + this.writeData.mailText + "\r\n" +
                "内容:\r\n" + this.writeData.contentsText + "\r\n";
            
            FileIO.SaveShiftJis(".ageon" + Path.DirectorySeparatorChar + "WriteToBoard", fileName, str);
        }
    }
}
