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;

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

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

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

        public IQueryable<CmUserGroup> Gets(int id, int siteId) {
            var data = _context.CmUserGroup.Where(x => x.UserGroupId == id && x.SiteId == siteId);
            return data;
        }

        public void Create(CmUserGroup data) {
            if (_context.CmUserGroup.Where(x => x.SiteId == data.SiteId && x.Name == data.Name).Count() > 0) {
                throw new ServiceException("이미 동일 이름이 존재합니다.");
            }
            _context.CmUserGroup.Add(data);
            _context.SaveChanges();
        }

        public void Edit(int id, int siteId, CmUserGroup data) {
            var persist = _context.CmUserGroup
                            .Where(x => x.UserGroupId == id && x.SiteId == siteId).FirstOrDefault();
            if (persist == null) {
                throw new ServiceException("정보를 찾을 수 없습니다.");
            }
            if (_context.CmUserGroup.Where(x => x.SiteId == siteId && x.Name == data.Name && x.UserGroupId != data.UserGroupId).Count() > 0) {
                throw new ServiceException("이미 동일 이름이 존재합니다.");
            }

            persist.SiteId = data.SiteId;
            persist.UserGroupId = data.UserGroupId;
            persist.Name = data.Name;
            _context.CmUserGroup.Update(persist);
            _context.SaveChanges();
        }

        public void Delete(int id, int siteId) {
            var data = _context.CmUserGroup.First(x => x.UserGroupId == id && x.SiteId == siteId);
            var userItemList = _context.CmUser.Where(x => x.UserGroupId == id && x.SiteId == siteId).ToList();
            if (userItemList.Count > 0) {
                throw new ServiceException("이미 사용중인 코드입니다.");
            }
            _context.CmUserGroup.Remove(data);
            _context.SaveChanges();
        }
    }
}