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 GuidelineService {
        private readonly ILogger<GuidelineService> _logger;
        private readonly FMSContext _context;
        private readonly StorageHelper _storage;
        private readonly AppSettings _appSettings;
        private readonly PushHelper _push;

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

        public void Save(CmGuideline data) {
            bool bCreate = false;
            using (var trans = new TransactionScope()) {

                var persist = _context.CmGuideline
                                .Where(x => x.SiteId == data.SiteId
                                    && x.GuidelineId == data.GuidelineId).FirstOrDefault();
                if (persist == null) {
                    bCreate = true;
                    var check = _context.CmGuideline.Where(x => x.SiteId == data.SiteId
                        && x.GuidelineId == data.GuidelineId).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 == "guideline");
                        data.CmFile.FileCategory = category;
                        data.CmFile.CreatedDate = DateTime.Now;
                    } else {
                        data.CmFile = null;
                    }

                    data.IsUse = true;
                    _context.CmGuideline.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 == "guideline");
                        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 file1");
                    } else if (data.CmFile != null && data.CmFile.IsDelete) {
                        persist.FileId = null;
                        persist.CmFile = null;
                        _logger.LogInformation("delete file1");
                    }
                    persist.Title = data.Title;
                    persist.BusinessFieldId = data.BusinessFieldId;
                    persist.Contents = data.Contents;
                    persist.AddDate = data.AddDate;
                    persist.UpdateDate = data.UpdateDate;
                    persist.IsAllView = data.IsAllView;
                    if (Util.S(persist.RegisterUserId) == "") {
                        persist.RegisterUserId = data.RegisterUserId;
                    }
                    _context.CmGuideline.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();
            }

            if (bCreate) {
                if (data.IsAllView != null && data.IsAllView == true) {
                    _push.SendToAllUsers("관리지침", data.Title, new {
                        type = "guideline",
                        id = data.GuidelineId
                    });
                } else {
                    _push.SendToSiteUsers(data.SiteId, "관리지침", data.Title, new {
                        type = "guideline",
                        id = data.GuidelineId
                    });
                }
            }
        }

        public void AddCount(int id) {
            var guideline = _context.CmGuideline.FirstOrDefault(x => x.GuidelineId == id);
            if (guideline != null) {
                guideline.ReadCount++;
                _context.CmGuideline.Update(guideline);
                _context.SaveChanges();
            }
        }

        public void Delete(int siteId, int guidelineId) {
            var data = _context.CmGuideline.First(x => x.SiteId == siteId && x.GuidelineId == guidelineId);
            _context.CmGuideline.Remove(data);
            _context.SaveChanges();
        }

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