using System;
using System.IO;
using System.Security;
using System.Web.UI;
using BeWo.Data;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.Security;

public partial class DocumentDownload : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!SessionFacade.IsUserLoggedIn())
            throw new SecurityException("Invalid authentication");

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

        if (SecurityUtils.CheckToken(token))
        {
            long lFSOID = long.Parse(this.Request.Params["faoid"]);

            
            
            try
            {
                FileAttachment lFA = DAOFactory.GenericDAO.LoadByID<FileAttachment>(lFSOID);


                if (lFA.Path != null)
                {
                    string lFileName = Path.GetFileName(lFA.Path);

                    Response.AddHeader("content-disposition", "attachment;filename=" + lFileName);
                    Response.Charset = "";
                    Response.ContentType = "application/" + Path.GetExtension(lFileName);
                }
                if (lFA.Data == null || lFA.Data.Length == 0)
                {
                    Response.Write("Dieses Dokument enthält keine Daten!");
                }
                else
                {
                    Response.BinaryWrite(lFA.Data);
                }
            }
            catch (Exception ex)
            {
                Response.Write(String.Format(
                    "Fehler beim öffnen des Dokuments!<p>Fehlermeldung: {0}</p><p>{1}</p>", ex.Message,
                    ex.StackTrace));
                if (ex.InnerException != null)
                    Response.Write(String.Format("<p>Inner Exception: {0}</p><p>{1}</p>", ex.InnerException.Message,
                                                    ex.InnerException.StackTrace));
            }

            
        }
        else
        {
            Response.Write("<p align=\"center\">Session ist abgelaufen!</p>");
        }
    }
}