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 System.Transactions;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using FMSAdmin.Models;

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

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

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

        public IQueryable<FmsFacilityState> Get(int id) {
            var data = _context.FmsFacilityState.Where(x => x.FacilityStateId == id);
            return data;
        }

        public IQueryable<FmsFacilityStateDetail> GetDetail(int id) {
            var data = _context.FmsFacilityStateDetail.Where(x => x.FacilityStateId == id);
            return data;
        }

        public void Create(FmsFacilityState data) {
            // if (data.StartDate <= DateTime.Today) {
            //     throw new ServiceException("시작일은 당일 이후로 설정하시기 바랍니다.");
            // }

            using (var transaction = _context.Database.BeginTransaction()) {
                int num = 1;
                foreach (var item in data.FmsFacilityStateDetail) {
                    item.QuestionId = num++;
                }
                _context.FmsFacilityState.Add(data);
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void Edit(int id, FmsFacilityState data) {
            var persist = _context.FmsFacilityState.Where(x => x.FacilityStateId == id).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }

            // if (persist.StartDate <= DateTime.Today) {
            //     throw new ServiceException("진행중인 질문은 수정할 수 없습니다.");
            // }
            if (persist.EndDate < DateTime.Today) {
                throw new ServiceException("완료된 질문은 수정할 수 없습니다.");
            }

            using (var transaction = _context.Database.BeginTransaction()) {
                //if (isAdmin == 1) {
                persist.Title = data.Title;
                persist.StartDate = data.StartDate;
                persist.EndDate = data.EndDate;
                persist.Note = data.Note;

                var oldDetailList = _context.FmsFacilityStateDetail.Where(x => x.FacilityStateId == persist.FacilityStateId && x.Type == 2).ToList();
                _context.FmsFacilityStateDetail.RemoveRange(persist.FmsFacilityStateDetail);
                _context.SaveChanges();
                int num = 1;
                foreach (var item in data.FmsFacilityStateDetail) {
                    persist.FmsFacilityStateDetail.Add(new FmsFacilityStateDetail() {
                        FacilityStateId = persist.FacilityStateId,
                        QuestionId = num,
                        Type = 1,
                        SiteId = null,
                        Content = item.Content
                    });

                    foreach (var item2 in oldDetailList.Where(f => f.QuestionId == item.QuestionId)) {
                        persist.FmsFacilityStateDetail.Add(new FmsFacilityStateDetail() {
                            FacilityStateId = persist.FacilityStateId,
                            QuestionId = num,
                            Type = 2,
                            SiteId = item2.SiteId,
                            Content = item2.Content
                        });
                    }
                    num = num + 1;
                }
                _context.FmsFacilityState.Update(persist);
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void Reply(int id, int siteId, FmsFacilityState data) {
            var persist = _context.FmsFacilityState.Where(x => x.FacilityStateId == id).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }

            if (persist.StartDate > DateTime.Today) {
                throw new ServiceException("대기중인 질문은 답변할 수 없습니다.");
            }
            if (persist.EndDate < DateTime.Today) {
                throw new ServiceException("완료된 질문은 답변할 수 없습니다.");
            }

            using (var transaction = _context.Database.BeginTransaction()) {
                var delList = persist.FmsFacilityStateDetail.Where(x => x.Type == 2 && x.SiteId == siteId);
                _context.FmsFacilityStateDetail.RemoveRange(delList);

                foreach (var item in data.FmsFacilityStateDetail) {
                    if (item.Type == 2 && item.SiteId == siteId && item.Content != "") {
                        FmsFacilityStateDetail detailList = new FmsFacilityStateDetail() {
                            FacilityStateId = id,
                            QuestionId = item.QuestionId,
                            Type = 2,
                            SiteId = siteId,
                            Content = item.Content
                        };
                        _context.FmsFacilityStateDetail.Add(detailList);
                    }
                }
                _context.SaveChanges();

                transaction.Commit();
            }
        }

        public void Delete(int id) {
            using (var trans = new TransactionScope()) {
                var data = _context.FmsFacilityStateDetail.Where(x => x.FacilityStateId == id);
                _context.FmsFacilityStateDetail.RemoveRange(data);

                var data2 = _context.FmsFacilityState.Where(x => x.FacilityStateId == id).FirstOrDefault();
                _context.FmsFacilityState.Remove(data2);
                _context.SaveChanges();
                trans.Complete();
            }
        }
    }
}