using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Runtime.Serialization;

namespace SilverlightWeb.portlets.Silverlight_sample
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]



    public class webFileHandler : IHttpHandler
    {



        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string mode = context.Request.QueryString["mode"];
                if (mode.StartsWith("download"))
                {
                    handleDownload(context);
                    return;
                }
                else
                {
                    context.Response.Status = "Request mode: " + mode + " not supported.";
                }
            }
            catch (System.Exception se)
            {
                context.Response.Status = se.Message;
            }
            context.Response.StatusCode = 500;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void handleDownload(HttpContext context)
        {
            string uploadPath = context.Server.MapPath("~/upload_tmp");
            string fileid = null;
            string mode = context.Request.QueryString["mode"];
            int i = mode.IndexOf("_");
            if (i > 0)
            {
                fileid = mode.Substring(i + 1);
            }

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            try
            {
                string filePath = DBTool.getFromDB(uploadPath, fileid);
                if (!String.IsNullOrEmpty(filePath))
                {
                    context.Response.ContentType = "application/octet-stream";
                    string fileName = Path.GetFileName(filePath);
                    // Set the filename
                    context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                    context.Response.WriteFile(filePath);
                    //File.Delete(filePath);
                    return;
                }
            }
            catch (System.Exception se)
            {
                context.Response.Status = se.Message;
            }
            context.Response.StatusCode = 500;
        }
    }



}
