using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BLL.Base;

using Model.UnitsOfWork;
using Model.Entities.Files.FS_Entities;
using Model.Entities.Files.Repo;
using Model.Entities.Users;

namespace BLL.Services.FS
{

    /// <summary>
    /// Сервис, контролирующий загрузку файлов
    /// </summary>
    public class UploadServices : BaseServices
    {
        const int ChunkSize = 1048576;
        protected readonly Repo_SFileUpload Repo_SFileUpload;

        public UploadServices(UOW UOW) : base(UOW)
        {
            Repo_SFileUpload = UOW.Repo_SFileUpload;
        }

        public SFileUpload StartUpload(SDirectory directory, string Name, long size, User user)
        {
            var res = Repo_SFileUpload.Create(
                new SFileUpload(directory, Name, size, ChunkSize, user));                

            return res;
        }
        public bool UploadChunk(SFileUpload project, byte[] data)
        {
            project.CurrentChunk = data;
            project.LastChunkUploaded = DateTime.Now;

            Repo_SFileUpload.Update(project);


            if (project.UploadProgress == 100)
            {
                Done(project);
                return true;
            }

            return false;
        }

        public void Cansel(SFileUpload project)
        {
            Repo_SFileUpload.Delete(project);
        }

        private void Done(SFileUpload project)
        {
            var p = project.Parent;
            var upload_user = project.User;

            Repo_SFileUpload.DeleteInList(project);

            UOW.Repo_SFile.Create(
                new SFile(p, project.Name, (long)project.Size, upload_user));          
        }

    }
}
