using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Zanetti.Data
{
    public class DownloadIndexFileDialog : Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.btnClose = new System.Windows.Forms.ToolStripButton();
            this.label = new System.Windows.Forms.ToolStripLabel();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.toolStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // toolStrip1
            // 
            this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.btnClose,
            this.label});
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Size = new System.Drawing.Size(344, 25);
            this.toolStrip1.TabIndex = 0;
            this.toolStrip1.Text = "toolStrip1";
            // 
            // btnClose
            // 
            this.btnClose.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
            this.btnClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(48, 22);
            this.btnClose.Text = "閉じる";
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            // 
            // label
            // 
            this.label.Name = "label";
            this.label.Size = new System.Drawing.Size(304, 18);
            this.label.Text = "OSDNにアクセスしています。お待ちください。";
            // 
            // textBox1
            // 
            this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.textBox1.Location = new System.Drawing.Point(0, 25);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox1.Size = new System.Drawing.Size(344, 1);
            this.textBox1.TabIndex = 1;
            // 
            // DownloadIndexFileDialog
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(344, 26);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.toolStrip1);
            this.Name = "DownloadIndexFileDialog";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Index.txt";
            this.Shown += new System.EventHandler(this.BrandIndex_Shown);
            this.toolStrip1.ResumeLayout(false);
            this.toolStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ToolStrip toolStrip1;
        private System.Windows.Forms.ToolStripButton btnClose;
        private System.Windows.Forms.ToolStripLabel label;
        private System.Windows.Forms.TextBox textBox1;

        public DownloadIndexFileDialog()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BrandIndex_Shown(object sender, EventArgs e)
        {
            this.btnClose.Enabled = false;
            MemoryStream ms = null;
            try
            {
                Env.Frame.Cursor = Cursors.WaitCursor;
                ms = Util.HttpDownload("http://protra.osdn.jp/data/index.txt");
                int dt = BrandCollection.GuessDate(ms);
                ms.Position = 0;
                if (dt > Env.BrandCollection.LastUpdatedDate)
                {
                    System.Collections.Generic.Dictionary<int, string> dic_org = new System.Collections.Generic.Dictionary<int, string>();
                    string[] lines = File.ReadAllLines(Env.GetAppDir() + "index.txt", Encoding.Default);
                    foreach (string line in lines)
                    {
                        string[] cols = line.Split(',');
                        int code = 0;
                        if (int.TryParse(cols[0], out code))
                            dic_org.Add(code, line);
                    }
                    label.Text = "新しいインデックスファイルをダウンロードしました。";
                    this.Width = 520;
                    this.Height = 400;
                    Util.StreamToFile(ms, Env.GetAppDir() + "index.txt");
                    StringBuilder sb = new StringBuilder();
                    ms.Seek(0, SeekOrigin.Begin);
                    TextReader tr = new StreamReader(ms, Encoding.Default);
                    while (tr.Peek() >= 0)
                    {
                        string line = tr.ReadLine();
                        string[] cols = line.Split(',');
                        int code = 0;
                        if (int.TryParse(cols[0], out code))
                        {
                            if (!dic_org.ContainsKey(code))
                                sb.AppendLine("新規銘柄:" + line);
                            else
                            {
                                if (dic_org[code] != line)
                                {
                                    sb.AppendLine("変更   ：" + line);
                                    sb.AppendLine("     旧：" + dic_org[code]);
                                }
                            }
                        }
                    }       //これを利用する手もあり
                    textBox1.Text = sb.ToString();
                    this.Refresh();
                    //MessageBox.Show(sb.ToString(), "新しいindex.txt");
                    dic_org.Clear();
                    Env.BrandCollection.Load(Env.GetAppDir() + "index.txt");    //そのまま更新
                    if (File.Exists(Env.GetAppDir() + "index_append.txt"))
                        Env.BrandCollection.Load(Env.GetAppDir() + "index_append.txt");
                    Env.Frame.Cursor = Cursors.Default;
                    label.Text = "銘柄情報が更新されました。";
                }
                else
                {
                    label.Text = "新しいインデックスファイルはありません。";
                }
            }
            catch (Exception ex)
            {
                Util.ReportCriticalError(ex);
            }
            finally
            {
                if (ms != null) ms.Close();
                this.btnClose.Enabled = true;
            }
        }
    }
}