using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Model.Entities.Base;
using Model.Entities.Files.FS_Entities;
using Model.Entities.Users;
using Model.UnitsOfWork;
using BLL.Services;

using Web.Models.Base;
using Model.ViewModel.Files;

namespace Web.Controllers.API
{
    class UploadInfo : BaseApiResult
    {
        public int UploadID { set; get; }

        public UploadInfo(
            Base.BaseController controller,
            bool Successe, 
            string Msg, 
            int UploadID) 
            : base(controller, Successe, Msg)
        {
            this.UploadID = UploadID;
        }
    }


    public class UploadFilesController : Base.BaseApiController
    {

        [HttpPost]
        public JsonResult StartUpload(int ParentID, string Name, long size)
        {           
            int ID;            

            try
            {
                var parent = UOW.Repo_SDirectory.All.FirstOrDefault(e => e.ID == ParentID);
                var proj = uploadServices.StartUpload(parent, Name, size, CurrentUser);

                ID = proj.ID;
            }
            catch (Exception ex)
            {
                return new UploadInfo(this, false, ex.FullMessage(), -1).ToJson;
            }

            return new UploadInfo(this, true, "", ID).ToJson;
        }



        [HttpPost]
        public JsonResult UploadBlob(UploadBlob model)
        {
            try
            {
                var prog = UOW.Repo_SFileUpload.All.
                    FirstOrDefault(e => e.ID == model.ID);

                if (prog == null)
                    return new UploadInfo(this, false, "Загрузка не найдена", model.ID).ToJson;


                uploadServices.UploadChunk(prog, model.ToByte());
            }
            catch (Exception ex)
            {
                return new UploadInfo(this, false, ex.FullMessage(), model.ID).ToJson;
            }


            return new UploadInfo(this, true, "", model.ID).ToJson;
        }

        [HttpPost]
        public JsonResult Cansel(int ID)
        {
            var prog = UOW.Repo_SFileUpload.All.
                FirstOrDefault(e => e.ID == ID);

            uploadServices.Cansel(prog);

            return new UploadInfo(this, true, "", ID).ToJson;
        }


    }
}