using System;
using System.IO;
using System.Security;
using System.Web.UI;

using BeWo.Data;

using BS.Shared.Core;
using BeWo.Service.Security;

public partial class Download : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!SessionFacade.IsUserLoggedIn())
            {
                throw new SecurityException("Invalid authentication");
            }

            var token = this.Request.Params["token"];

            if (SecurityUtils.CheckToken(token))
            {
                string lFileID = this.Request.Params["fileid"];
                string lPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, lFileID + ".tmp");

                using (FileStream uFileStream = File.Open(lPath, FileMode.Open))
                {
                    using (StreamReader uSr = new StreamReader(uFileStream))
                    {
                        this.Response.Write(Utils.MyHtmlEncode(uSr.ReadToEnd()));
                    }
                }

                File.Delete(lPath);

                this.Response.AddHeader("content-disposition", "attachment;filename=BeWoDokument" + Path.GetExtension(lFileID));
                this.Response.Charset = string.Empty;
                this.Response.ContentType = "application/" + Path.GetExtension(lFileID);

                this.Response.End();
            }
            else
            {
                this.Response.Write("Ungültiger Link!");
            }
        }
        catch (Exception ex)
        {
            this.Response.Write(ex.ToString());
        }
    }
}