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

namespace AgeOnUpdate
{
    class DownloadUpdateFile
    {
        public string httpResData;

        //public MemoryStream httpResRawData;
        public int httpResRawDataLength;

        private ManualResetEvent allDone;

        private string datUrl;

        public string command = "";


        const int BUFFER_SIZE = 4096;

        public DownloadUpdateFile()
        {
            httpResData = "";
        }

        public string Download(ref string responseStatusCode, ref string command, string accessUrl)
        {
            this.datUrl = accessUrl;

            allDone = new ManualResetEvent(false);

            Uri u = new Uri(accessUrl);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(u);
            req.KeepAlive = false;
            req.ProtocolVersion = HttpVersion.Version11;
            req.Method = "GET";

            req.AutomaticDecompression = DecompressionMethods.GZip;
            req.Timeout = 30000;

            req.Proxy = null;

            RequestState myRequestState = new RequestState();
            myRequestState.request = req;


            // Start the asynchronous request.
            IAsyncResult result =
              (IAsyncResult)req.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

            allDone.WaitOne();

            //次の動作を取得
            command = myRequestState.command;
            //エラーの数字を取得
            responseStatusCode = myRequestState.responseStatusCode;

            if (myRequestState.responseStatusCode.StartsWith("20") == true)
            {
                ;
            }
            else
            {
                try
                {
                    myRequestState.response.Close();
                }
                catch { ;}
                return "";
            }

            //--受信したデータを見る
            if ((httpResData == null) || (httpResData.Length < 1))
            {
                myRequestState.responseStatusCode = "996";
                myRequestState.command = "終了";
                try
                {
                    myRequestState.response.Close();
                }
                catch { ;}
                return "";
            }

            myRequestState.response.Close();

            return httpResData;
        }

        private void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
                HttpWebRequest myHttpWebRequest = myRequestState.request;


                try
                {
                    myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);

                    if (myRequestState.response.StatusCode == HttpStatusCode.OK)
                    {
                        myRequestState.responseStatusCode = "200";
                        myRequestState.command = "終了";
                    }
                    else if (myRequestState.response.StatusCode == HttpStatusCode.PartialContent)
                    {
                        myRequestState.responseStatusCode = "206";
                        myRequestState.command = "終了";
                    }
                }
                catch (System.Net.WebException e)
                {
                    if (e.Message.Contains("304") == true)
                    {
                        //変更が無い
                        myRequestState.responseStatusCode = "304";
                        myRequestState.command = "終了";
                        allDone.Set();
                        return;
                    }

                    else if (e.Message.Contains("302") == true)
                    {
                        //見つからない
                        allDone.Set();
                        return;
                    }
                    else if (e.Message.Contains("403") == true)
                    {
                        //ぼぼん規制
                        myRequestState.responseStatusCode = "403";
                        myRequestState.command = "終了";
                        allDone.Set();
                        return;
                    }
                    else if (e.Message.Contains("404") == true)
                    {
                        //見つからない
                        myRequestState.responseStatusCode = "404";
                        myRequestState.command = "過去ログ０";
                        allDone.Set();
                        return;
                    }
                    else
                    {
                        //それ以外の場合
                        myRequestState.responseStatusCode = "999";
                        myRequestState.command = "終了";
                        return;
                    }
                }
                catch
                {
                    //新規データが無い時にエラーが帰ることがある
                    myRequestState.responseStatusCode = "998";
                    myRequestState.command = "終了";
                    allDone.Set();
                    return;
                }

                Stream responseStream = myRequestState.response.GetResponseStream();
                myRequestState.streamResponse = responseStream;

                try
                {
                    Stream st = myRequestState.streamResponse;
                    //文字列データ
                    StreamReader sr;

                    sr = new StreamReader(st, System.Text.Encoding.GetEncoding("shift-jis"));

                    string str;

                    str = sr.ReadToEnd();
                    myRequestState.responseData.Append(str);
                }
                catch { ;}

                IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
                return;
            }
            catch
            { ;}
        }

        private void ReadCallBack(IAsyncResult asyncResult)
        {
            RequestState myRequestState = (RequestState)asyncResult.AsyncState;
            Stream st = myRequestState.streamResponse;

            StreamReader sr;

            sr = new StreamReader(st, System.Text.Encoding.GetEncoding("shift-jis"));

            string str;
            try
            {
                str = sr.ReadToEnd();

                if (str.Length > 0)
                {
                    myRequestState.responseData.Append(str);
                    try
                    {
                        IAsyncResult asynchronousResult = st.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
                        sr.Close();
                        st.Close();
                        return;
                    }
                    catch
                    {
                    }
                }
                else
                {
                }
            }
            catch { ;}

            if (myRequestState.responseData.Length > 1)
            {
                //文字列データ
                this.httpResData = myRequestState.responseData.ToString();

                Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");
                this.httpResRawDataLength = sjisEnc.GetByteCount(this.httpResData);
            }

            myRequestState.streamResponse.Close();

            sr.Close();
            st.Close();

            allDone.Set();
        }
    }
}