using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

namespace OnlineEditorsExample
{
    /// <summary>
    /// Summary description for FileSave
    /// </summary>
    public class FileSave : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string body;
            var PATH_FOR_SAVE = _Default.StoragePath + @"Return\";
            var fileName = context.Request["filename"] != string.Empty ? context.Request["filename"] : "unknown_" + DateTime.Now.ToString("yyyy-MM-dd_hh_mm");
            
            if (!Directory.Exists(PATH_FOR_SAVE))
            {
                Directory.CreateDirectory(PATH_FOR_SAVE);
            }

            using (var reader = new StreamReader(context.Request.InputStream))
                body = reader.ReadToEnd();

            var fileData = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(body);
            if ((int)fileData["status"] == 2)
            {
                var req = WebRequest.Create((string)fileData["url"]);

                using (var stream = req.GetResponse().GetResponseStream())
                using (var fs = File.Open(PATH_FOR_SAVE + fileName, FileMode.Create))
                {
                    var buffer = new byte[4096];
                    int readed;
                    while ((readed = stream.Read(buffer, 0, 4096)) != 0)
                        fs.Write(buffer, 0, readed);
                }
            }
            context.Response.Write("{\"error\":0}");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}