//ライセンス情報は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 nispi
{
    public class DownloadUpdateCheckFile
    {
        public string httpResData;

        //public MemoryStream httpResRawData;
        public int httpResRawDataLength;

        private ManualResetEvent allDone;
        private string datUrl;

        public string command = "";

        //private string dir;
        //private string datFileName;

        const int BUFFER_SIZE = 4096;

        public DownloadUpdateCheckFile()
        {
            httpResData = "";
        }

        public bool Download(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 = 10000;
            
            req.Proxy = null;

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


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

            allDone.WaitOne();

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

            //--受信したデータを見る
            if ((httpResData == null) || (httpResData.Length < 1))
            {
                myRequestState.response.Close();
                return false;
            }

            myRequestState.response.Close();
            return true;
        }


        private void RespCallback2(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 = "終了";
                    }
                }
                catch (System.Net.WebException e)
                {
                    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 = "終了";
                        allDone.Set();
                        return;
                    }
                }
                catch
                {
                    //新規データが無い時にエラーが帰ることがある
                    myRequestState.responseStatusCode = "998";
                    myRequestState.command = "終了";
                    allDone.Set();
                    return;
                }
                Stream responseStream = myRequestState.response.GetResponseStream();
                myRequestState.streamResponse = responseStream;
                Stream st = myRequestState.streamResponse;
                try
                {
                    //読み込んでしまった本文を読み込む
                    //バイナリデータ
                    byte[] array = ReadBinaryData(st);
                    myRequestState.memoryStream.Write(array, myRequestState.offset, array.Length);
                    myRequestState.offset += array.Length;
                }
                catch { ;}

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


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

            byte[] array;
            try
            {
                //バイナリデータ
                array = ReadBinaryData(st);
                myRequestState.memoryStream.Write(array, myRequestState.offset, array.Length);
                myRequestState.offset += array.Length;

                if (array.Length > 0)
                {
                    try
                    {
                        IAsyncResult asynchronousResult = st.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack2), myRequestState);
                        st.Close();
                        return;
                    }
                    catch { ;}
                }
            }
            catch { ;}

            if (myRequestState.offset > 1)
            {
                //バイナリデータ
                MemoryStream ms = new MemoryStream(myRequestState.memoryStream.GetBuffer());

                this.httpResRawDataLength = (int)ms.Length;
                this.httpResData = System.Text.Encoding.GetEncoding(932).GetString(ms.ToArray());

                ms.Dispose();
            }

            myRequestState.streamResponse.Close();
            //myRequestState.response.Close();
            st.Close();

            allDone.Set();
        }

        static public byte[] ReadBinaryData(Stream st)
        {
            byte[] buf = new byte[32768]; // 一時バッファ

            using (MemoryStream ms = new MemoryStream())
            {

                while (true)
                {
                    // ストリームから一時バッファに読み込む
                    int read = st.Read(buf, 0, buf.Length);

                    if (read > 0)
                    {
                        // 一時バッファの内容をメモリ・ストリームに書き込む
                        ms.Write(buf, 0, read);
                    }
                    else
                    {
                        break;
                    }
                }
                // メモリ・ストリームの内容をバイト配列に格納
                return ms.ToArray();
            }
        }
    }
}