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

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;

namespace FMSAdmin.Services {
    public class ReportHistoryService {
        private readonly ILogger<ReportHistoryService> _logger;
        private readonly FMSContext _context;
        private readonly StorageHelper _storage;

        public ReportHistoryService(
            ILogger<ReportHistoryService> logger,
            FMSContext context,
            StorageHelper storage) {
            _logger = logger;
            _context = context;
            _storage = storage;
        }

        public void Save(BemsReportHistory data) {

            using (var trans = new TransactionScope()) {



                var persist_1 = 0;
                var FormatName = _context.BemsReportFormat.Where(x => x.SiteId == data.SiteId && x.ReportFormatId == data.ReportFormatId).Select(x => x.FormatName).First();

                if (data.Seq == 0) {

                    var iCnt = _context.BemsReportHistory.Where(x => x.SiteId == data.SiteId).Count();
                    if (iCnt > 0) persist_1 = _context.BemsReportHistory.Where(x => x.SiteId == data.SiteId).Max(x => x.Seq);
                    else persist_1 = 0;
                    data.Seq = persist_1 + 1;
                }

                var persist = _context.BemsReportHistory
                                .Where(x => x.SiteId == data.SiteId && x.Seq == data.Seq).FirstOrDefault();
                if (persist == null) {


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

                    } else {
                        data.CmFile = null;
                    }


                    data.FormatName = FormatName;
                    data.CreateDate = DateTime.Now;


                    _context.BemsReportHistory.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 == "report");
                        persist.CmFile = new CmFile {
                            SiteId = data.SiteId,
                            FileCategory = category,
                            CreatedDate = DateTime.Now,
                            Name = data.CmFile.Name,
                            FileSize = data.CmFile.FileSize,
                            ContentType = data.CmFile.ContentType,
                        };

                    } else if (data.CmFile != null && data.CmFile.IsDelete) {
                        persist.FileId = null;
                        persist.CmFile = null;

                    }


                    persist.ReportName = data.ReportName;
                    persist.ReportFormatId = data.ReportFormatId;
                    persist.FormatName = FormatName;

                    // if (data.CmFile != null && data.CmFile.IsUpload) {
                    //     persist.CmFile = data.CmFile;
                    // }

                    persist.BemsReportHistoryContent.Clear();

                    // 추가된 일지 생성
                    foreach (var info in data.BemsReportHistoryContent) {
                        persist.BemsReportHistoryContent.Add(new BemsReportHistoryContent() {
                            SiteId = persist.SiteId,
                            Seq = persist.Seq,
                            ContentId = info.ContentId,
                            Content = info.Content,
                        });
                    }

                    _context.BemsReportHistory.Update(persist);


                    _context.SaveChanges();

                    if (data.CmFile != null && data.CmFile.IsUpload) {
                        // 카피
                        _storage.CopyEntity(data.CmFile.Path, persist.CmFile);
                        if (persist.CmFile != null) {
                            // 파일 삭제시 진짜 DB삭제?
                        }
                    }

                }
                trans.Complete();

            }
        }

        public IQueryable<BemsReportHistory> GetAll() {
            var query = _context.BemsReportHistory;//.AsNoTracking();
            return query;


        }

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

        public void Delete(int Seq, int siteId) {
            using (var trans = new TransactionScope()) {
                var data = _context.BemsReportHistory.First(x => x.Seq == Seq && x.SiteId == siteId);
                var detail = _context.BemsReportHistoryContent.Where(x => x.Seq == Seq && x.SiteId == siteId);

                _context.BemsReportHistoryContent.RemoveRange(detail);
                _context.BemsReportHistory.Remove(data);
                _context.SaveChanges();
                trans.Complete();
            }
        }
    }
}