// Copyright(C) 2008, 2010 panacorn <panacoran@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: KabukaJohoUpdator.cs 306 2010-03-19 13:21:22Z panacoran $

using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Text;
using Protra.Lib.Db;

namespace Protra.Lib.Update
{
	/// <summary>
	/// 株価情報を利用して株価データの更新を行うクラス。
	/// </summary>
	public class KabukaJohoUpdator: PriceDataUpdator
	{
        Hashtable mnameTable;
        int mnameYear;

        /// <summary>
        /// データが存在する最初の日付を取得する。
        /// </summary>
        public override DateTime DataSince
        {
            get { return new DateTime(2000, 1, 4); }
        }

        /// <summary>
		/// 株価データを更新する。
		/// </summary>
		/// <param name="worker">BackgroundWorker</param>
        /// <param name="e">DoWorkイベントの引数</param>
		public override void Update(BackgroundWorker worker, DoWorkEventArgs e)
		{
            DateTime begin = (DateTime)e.Argument;
            if (begin < DataSince)
                begin = DataSince;
			DateTime today = DateTime.Now;
			// 新しいデータが置かれるのは早くても午後4時以降
			if (today.Hour < 16)
				today = today.AddDays(-1);

            for (Start(begin, today); ShouldContinue(); NextDate())
			{
				UpdateProgress(worker, e);

                if (Date.Year >= 2006 && Date.Year != mnameYear)
                {
                    ReadMName();
                    mnameYear = Date.Year;
                }

                StartDownload();
                DownloadUtil.Url =
                    "http://www.edatalab.net/kabu/data" +
                    Date.ToString((Date.Year < 2006)
                               ? @"yyyy\/yyyyMMdd"
                               : @"yyyy\/\DyyMMdd") + ".LZH";
                Stream stream = DownloadUtil.DownloadAndExtract();
                if (stream == null)
                {
                    DecrementTotalDays();
                    continue;
                }
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    stream.Close();
                    return;
                }
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift_jis"));
                ArrayList dataList = new ArrayList();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    PriceData tmp = ParseLine(line);
                    if (tmp != null &&
                        (tmp.Code <= 1002 || tmp.Code >= 1300)) //各種指数は除外する。
                        dataList.Add(tmp);
                }
                reader.Close();
                TotalRecords = dataList.Count;
                EndDownload();

                for (; NumRecords < TotalRecords; IncrementRecords(), UpdateProgress(worker, e))
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        PriceTable.Delete(Date);
                        return;
                    }
                    
                    PriceData data = (PriceData)dataList[NumRecords];
                    Brand brand = BrandTable.GetRecordOrCreate(data.MarketId, data.Code, data.Name);
                    PriceTable.Add(brand.Id, data.Date, data.Open, data.High, data.Low, data.Close, data.Volume);
                }
                IncrementDays();
            }

			UpdateSplitData(worker, e);
            worker.ReportProgress(100, "");
		}

        private void ReadMName()
        {
            DownloadUtil.Url =
                "http://www.edatalab.net/kabu/data" +
                Date.ToString("yyyy") + "/MNAME.LZH";
            mnameTable = new Hashtable();
            Stream stream = DownloadUtil.DownloadAndExtract();
            if (stream == null)
                throw new ApplicationException("銘柄名データのダウンロードに失敗しました。");
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift_jis"));
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] tokens = line.Split(',');
                try
                {
                    mnameTable.Add(int.Parse(tokens[0]), tokens[1].Trim('"'));
                }
                catch (FormatException)
                {
                    continue;
                }
            }
            reader.Close();
        }

        /// <summary>
        /// 文字列に含まれるデータを格納したオブジェクトを返す。
        /// </summary>
        /// <param name="line">文字列を指定する。</param>
        /// <returns>オブジェクト</returns>
        private PriceData ParseLine(string line)
        {
            string[] tokens = line.Split(',');
            PriceData r = new PriceData();
            try
            {
                int i = 0;
                r.Date = DateTime.Parse(tokens[i++]);
                r.Code = int.Parse(tokens[i++]);
                if (r.Date.Year < 2006)
                    r.Name = tokens[i++].Trim('"');
                else
                    r.Name = (string)mnameTable[r.Code];
                if (r.Date.Year >= 2006)
                {
                    switch (int.Parse(tokens[i++]))
                    {
                        case 1:
                            r.MarketId = Db.MarketId.Tokyo1;
                            break;
                        case 2:
                            r.MarketId = Db.MarketId.Tokyo2;
                            break;
                        case 3:
                            r.MarketId = Db.MarketId.Mothers;
                            break;
                        case 4:
                            r.MarketId = Db.MarketId.Jasdaq;
                            break;
                        case 6:
                            r.MarketId = Db.MarketId.Osaka1;
                            break;
                        case 7:
                            r.MarketId = Db.MarketId.Osaka2;
                            break;
                        case 8:
                            r.MarketId = Db.MarketId.Hercules;
                            break;
                        default:
                            return null;
                    }
                }
                if (r.Name == null)
                {
                    // 2006年以降のデータでは、上場廃止で銘柄名が得られない場合がある。
                    // データベースに名前があればそれで補うが、なければデータを破棄する。
                    Brand brand = BrandTable.GetRecord(r.MarketId, r.Code);
                    if (brand == null)
                        return null;
                    r.Name = brand.Name;
                }
                
                // 指数の値に小数が含まれているのでdouble.Parseを利用する。
                r.Open = (int)double.Parse(tokens[i++]);
                r.High = (int)double.Parse(tokens[i++]);
                r.Low = (int)double.Parse(tokens[i++]);
                r.Close = (int)double.Parse(tokens[i++]);
                r.Volume = double.Parse(tokens[i++]) / 1000;
                if (r.Date.Year < 2006)
                {
                    switch (int.Parse(tokens[i++]))
                    {
                        case 1:
                            r.MarketId = Db.MarketId.Tokyo1;
                            break;
                        case 2:
                            r.MarketId = Db.MarketId.Tokyo2;
                            break;
                        case 3:
                            r.MarketId = Db.MarketId.Jasdaq;
                            break;
                        default:
                            return null;
                    }
                }
            }
            catch (FormatException)
            {
                // フォーマットエラーは全部無視する。
                return null;
            }
            return r;
        }
	}
}
