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

using System.IO;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data;

using Web.Models.Base;

using Model.Entities.Files;
using Model.Entities.Files.FS_Entities;
using BLL.Services;
using BLL.Services.FS;
using Model.UnitsOfWork;

namespace Web.Controllers.API
{
    class ViewModelItems : BaseApiResult
    {
        public int ParentID { set; get; }
        public string LogicPath { set; get; }
        public string ParentName { set; get; }
        public int CurrentID { set; get; }


        public List<string> Path;

        public List<ViewModelItem> items = new List<ViewModelItem>();

        public ViewModelItems(bool Successe, string ResMessage)
            : base(Successe, ResMessage, "GetDirectoryItems") { }

    }
    class ViewModelItem
    {
        public int ID { set; get; }
        public string Name { set; get; }
        public string Type { set; get; }
        public string Size { set; get; }
    }

    public class DeleteResult : BaseApiResult
    {
        public DeleteResult(bool Successe, string ResMessage)
             : base(Successe, ResMessage, "DeleteFile") { }
    }

    public class ExplorerController : Base.BaseApiController
    {
        [HttpGet]
        public JsonResult GetDirectoryItems(int ID)
        {
            ViewModelItems json;

            if (ID == -1)
            {
                //#Data #Permission
                //Выбрать корренные папки, к которым имеет доступ текущий пользователь
                var data = UOW.Repo_SRootDirectory.All_NoTrack_List.
                    Where(e => permissionServices.CanOpen(CurrentUser, e)).ToList();

                json = new ViewModelItems(true, "")
                {
                    ParentID = -1,
                    LogicPath = @"\",
                    ParentName = "Корень",
                    CurrentID = ID
                };

                data.ForEach((e) =>
                {
                    json.items.Add(new ViewModelItem()
                    {
                        ID = e.ID,
                        Name = e.Name,
                        Type = e.Type.ToString()
                    });
                });

                return Json(json, JsonRequestBehavior.AllowGet);
            }
            else
            {
                //#Data
                var data = UOW.Repo_SDirectory.All_NoTrack.
                    Where(e => e.ID == ID).
                    Include(e => e.Root).
                    Include("_Items").
                    First();

                //#Permission
                if (!permissionServices.CanOpen(CurrentUser, data))
                {
                    var json_PError = new ViewModelItems(false, "CanOpen permission error")
                    {
                        PermissionError = true
                    };

                    return Json(json_PError, JsonRequestBehavior.AllowGet);
                }



                json = new ViewModelItems(true, "")
                {
                    ParentID = data.IsRoot ? -1 : data.Parent_ID.Value,
                    LogicPath = data.LogicPath,
                    ParentName = data.IsRoot ? "Корень" : data.Parent.Name
                };

                data.Items.ToList().ForEach((e) =>
                {
                    if (e.Type == Enum_BaseDirectoryEntity.UploadFile)
                        return;

                    json.items.Add(new ViewModelItem()
                    {
                        ID = e.ID,
                        Name = e.Name,
                        Type = e.Type.ToString(),
                        Size = (e is SFile) ? e.GetSize(Enum_FileSize.MByte).ToString() : ""
                    });
                });

                return Json(json, JsonRequestBehavior.AllowGet);
            }
        }


        [HttpGet]
        public FileResult GetFile(int ID)
        {
            //#Data
            var file = UOW.Repo_SFile.All_NoTrack.
                FirstOrDefault(e => e.ID == ID);

            //#Permission
            if (!permissionServices.CanDownload(CurrentUser, file.Root))
            {
                MemoryStream res = new MemoryStream();

                return File(res, "application/octet-stream", "CanDownload permission error");
            }


            return File(file.Info.Open(FileMode.Open, FileAccess.Read), "application/octet-stream", file.Name);
        }

        [HttpPost]
        public JsonResult DeleteFile(int ID)
        {
            //try
            //{
                //#Data
                var file = UOW.FS_Items.FirstOrDefault(e => e.ID == ID);

                //#Permission
                if (!permissionServices.CanUpload(CurrentUser, file.Root))
                {
                    var json_PError = new ViewModelItems(false, "CanOpen permission error")
                    {
                        PermissionError = true
                    };

                    return Json(json_PError);
                }

                UOW.Delete(file);
            //}
            //catch (Exception ex)
            //{
                //var json_err = new DeleteResult(false, ex.Message);

                //return Json(json_err, JsonRequestBehavior.AllowGet);
           // }

            var json = new DeleteResult(true, "");

            return Json(json);
        }



        [HttpGet]
        public async Task<JsonResult> ScanDirectory(int ID)
        {
            if (ID == -1)
            {
                var dir = UOW.Repo_SRootDirectory.All_List;
                new ConfigurationServices(UOW).
                    ReadConfiguration();
                await new ScanServices(UOW).ScanAllDirs();
            }
            else
            {
                var dir = UOW.Repo_SDirectory.All.
                    FirstOrDefault(e => e.ID == ID);
                await new ScanServices(UOW).
                    RecursScanDirectoryAsync(dir, false);


                //var items = UOW.context.FS_Items.
                //    FirstOrDefault(e => e.ID == ID).Items.ToList();
            }


            return Json(true, JsonRequestBehavior.AllowGet);
        }



        [HttpPost]
        public JsonResult MoveElement(int ID, int NewParent)
        {
            //Перемещаемый элемент
            var elem = UOW.FS_Items.FirstOrDefault(e => e.ID == ID);
            //Папка в которую будет выполняться перемещение
            var new_parent = UOW.Repo_SDirectory.All.FirstOrDefault(e => e.ID == NewParent);


            if (permissionServices.CanUpload(CurrentUser, elem.Parent) &&
                permissionServices.CanUpload(CurrentUser, new_parent))
            {
                return Json(false);
            }

            elem.Parent = new_parent;
            UOW.Update(elem);

            return Json(true);
        }

        [HttpPost]
        public JsonResult CreateDirectory(int ParentID, string Name)
        {
            //#Data
            var parent = UOW.Repo_SDirectory.All.
                FirstOrDefault(e => e.ID == ParentID);

            //#Permission
            if (!permissionServices.CanUpload(CurrentUser, parent))
            {
                return Json(false);
            }

            UOW.Repo_SDirectory.
                Create(new SDirectory((SDirectory)parent, Name, CurrentUser));

            return Json(true);
        }

    }
}