using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

using FMSAdmin.Data;
using FMSAdmin.Helpers;
using FMSAdmin.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using FMSAdmin.Models;
using System.Transactions;

namespace FMSApp.Services {
    public class ManualHistoryService {
        private readonly ILogger<ManualHistoryService> _logger;
        private readonly FMSContext _context;

        private readonly AppSettings _appSettings;
        private readonly StorageHelper _storage;

        public ManualHistoryService(
            ILogger<ManualHistoryService> logger,
            FMSContext context,
            IOptions<AppSettings> appSettings,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _appSettings = appSettings.Value;
            _storage = storage;
        }

        public void Save(FmsManualHistory data) {
            using (var trans = new TransactionScope()) {

                var persist = _context.FmsManualHistory
                                .Where(x => x.SiteId == data.SiteId
                                    && x.ManualId == data.ManualId
                                    && x.HistoryId == data.HistoryId).FirstOrDefault();
                if (persist == null) {
                    var check = _context.FmsManualHistory.Where(x => x.SiteId == data.SiteId
                                                            && x.ManualId == data.ManualId
                                                            && x.HistoryId == data.HistoryId).Count();
                    if (check > 0) {
                        throw new ServiceException("아이디가 중복됩니다.");
                    }

                    if (data.CmFile != null && data.CmFile.IsUpload) {
                        data.CmFile.SiteId = data.SiteId;
                        var category = _context.CmFileCategory.First(x => x.Name == "manual");
                        data.CmFile.FileCategory = category;
                        data.CmFile.CreatedDate = DateTime.Now;
                    } else {
                        data.CmFile = null;
                    }

                    data.UpdatedDate = DateTime.Now;
                    _context.FmsManualHistory.Add(data);
                    _context.SaveChanges();

                    if (data.CmFile != null && data.CmFile.IsUpload) {
                        // 카피
                        _storage.CopyEntity(data.CmFile.Path, data.CmFile);
                    }
                } else {
                    if (data.CmFile != null && data.CmFile.IsUpload) {
                        var category = _context.CmFileCategory.First(x => x.Name == "manual");
                        persist.CmFile = new CmFile {
                            SiteId = data.SiteId,
                            FileCategory = category,
                            CreatedDate = DateTime.Now,
                            Name = data.CmFile.Name,
                            FileSize = data.CmFile.FileSize,
                            ContentType = data.CmFile.ContentType,
                        };
                        _logger.LogInformation("upload file");
                    } else if (data.CmFile != null && data.CmFile.IsDelete) {
                        persist.FileId = null;
                        persist.CmFile = null;
                        _logger.LogInformation("delete file");
                    }

                    persist.UpdatedUserId = data.UpdatedUserId;
                    persist.UpdatedDate = DateTime.Now;
                    persist.RevisionNo = data.RevisionNo;
                    persist.Description = data.Description;
                    _context.FmsManualHistory.Update(persist);
                    _context.SaveChanges();

                    if (data.CmFile != null && data.CmFile.IsUpload) {
                        // 카피
                        _storage.CopyEntity(data.CmFile.Path, persist.CmFile);
                    }
                }
                trans.Complete();
            }
        }

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

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