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

namespace nispi
{
    partial class Shiori
    {
        public string beforeShioriStr = "";
        public string datName = "";

        public Mutex mutex = new Mutex(false, "Shiori");

        BrowserParts browserParts;

        public string datUrl = "";
        public string datDirPath = "";

        public Shiori(BrowserParts browserParts)
        {
            this.browserParts = browserParts;
        }

        private string ResetXML()
        {
            XNamespace ns = "Shiori";
            XElement doc = new XElement(ns + "Option",
                new XElement(ns + "BeforeShioriStr", "0"));

            FileIO.SaveShiftJis(datDirPath, datName + "shiori.xml", doc.ToString());

            return doc.ToString();
        }

        public void GetXMLData(string datUrl)
        {
            datName = Util.DatUrlToThreadID(datUrl);
            datDirPath = Util.DatUrlToDatDirRelativePath(datUrl);
            mutex.WaitOne();

            //datDirPathがフルパスになっているので読込先でエラーが起きる。
            string str = FileIO.ReadShiftJis(datDirPath, datName + "shiori.xml");

            if ((str == null) || (str.Length == 0))
                str = ResetXML();

            try
            {
                XNamespace ns = "Shiori";
                XDocument doc = XDocument.Parse(str);
                XElement doc2 = doc.Element(ns + "Option");

                this.BeforeShioriStr = doc2.Element(ns + "BeforeShioriStr").Value;

                //SetShiori(this.BeforeShioriStr);
            }
            catch { ;}
            mutex.ReleaseMutex();
        }

        public void SaveToFile()
        {
            mutex.WaitOne();

            XNamespace ns = "Shiori";
            XElement doc = new XElement(ns + "Option",
                new XElement(ns + "BeforeShioriStr", this.BeforeShioriStr));

            FileIO.SaveShiftJis(datDirPath, datName + "shiori.xml", doc.ToString());

            mutex.ReleaseMutex();
        }

        public string BeforeShioriStr
        {
            set
            {
                mutex.WaitOne();
                beforeShioriStr = value;
                mutex.ReleaseMutex();
            }
            get
            {
                string data;
                mutex.WaitOne();
                data = beforeShioriStr;
                mutex.ReleaseMutex();
                return data;
            }
        }

    }
}
