using System;
using System.Linq;
using System.Transactions;
using FMSAdmin.Data;
using FMSAdmin.Entities;
using FMSAdmin.Helpers;
using Microsoft.Extensions.Logging;

namespace FMSAdmin.Services {
    public class ManualService {
        private readonly ILogger<ManualService> _logger;
        private readonly FMSContext _context;
        private readonly StorageHelper _storage;
        public ManualService(
            ILogger<ManualService> logger,
            FMSContext context,
            StorageHelper storage) {
            _logger = logger;
            _context = context;
            _storage = storage;
        }


        public void Create(FmsManual data) {
            using (var trans = new TransactionScope()) {
                checkName(data);
                if (data.CmFile != null && data.CmFile.IsUpload) {
                    var category = _context.CmFileCategory.First(x => x.Name == "manual");
                    data.CmFile.FileCategory = category;
                    data.CmFile.CreatedDate = DateTime.Now;
                } else {
                    data.CmFile = null;
                }
                data.FmsManualHistory.Add(new FmsManualHistory {
                    SiteId = data.SiteId,
                    RevisionNo = 0,
                    Description = data.Description,
                    CmFile = data.CmFile,
                    UpdatedDate = DateTime.Now,
                    UpdatedUserId = data.CreateUserId
                });

                _context.FmsManual.Add(data);
                _context.SaveChanges();
                if (data.CmFile != null && data.CmFile.IsUpload) {
                    // 카피
                    _storage.CopyEntity(data.CmFile.Path, data.CmFile);
                }

                trans.Complete();
            }
        }

        public void Edit(int id, int siteId, FmsManual data) {
            using (var trans = new TransactionScope()) {
                var persist = _context.FmsManual
                                .Where(x => x.ManualId == id && x.SiteId == siteId).FirstOrDefault();
                if (persist == null) {
                    throw new ServiceException("정보를 찾을 수 없습니다.");
                }
                if (!persist.Name.Equals(data.Name)) {
                    checkName(data);
                }

                persist.SiteId = data.SiteId;
                persist.ManualTypeId = data.ManualTypeId;
                persist.ManualGroupId = data.ManualGroupId;
                persist.ManualNo = data.ManualNo;
                persist.Name = data.Name;
                persist.Description = data.Description;

                _context.FmsManual.Update(persist);
                _context.SaveChanges();

                trans.Complete();
            }
        }

        public void checkName(FmsManual data) {
            var check = _context.FmsManual
                        .Where(x => x.SiteId == data.SiteId
                        && x.ManualGroupId == data.ManualGroupId
                        && x.ManualTypeId == data.ManualTypeId
                        && x.Name == data.Name).Count();
            if (check > 0) {
                throw new ServiceException("이미 동일 정보가 존재합니다.(메뉴얼 분류, 메뉴얼 유형, 메뉴얼명 확인 필요)");
            }
        }

        public void Delete(int id, int siteId) {
            var data = _context.FmsManual.First(x => x.ManualId == id && x.SiteId == siteId);
            _context.FmsManual.Remove(data);
            _context.SaveChanges();
        }

        public IQueryable<FmsManual> GetAll() {
            var query = _context.FmsManual;
            return query;
        }

        public IQueryable<FmsManual> Get(int id, int siteId) {
            var data = _context.FmsManual.Where(x => x.ManualId == id && x.SiteId == siteId);
            return data;
        }

    }
}