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 CompanyTypeService {
        private readonly ILogger<CompanyTypeService> _logger;
        private readonly FMSContext _context;

        public CompanyTypeService(
            ILogger<CompanyTypeService> logger,
            FMSContext context) {
            _logger = logger;
            _context = context;
        }

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

        public IQueryable<CmCompanyType> Gets(int id) {
            var data = _context.CmCompanyType.Where(x => x.CompanyTypeId == id/* && x.SiteId == siteId*/);
            return data;
        }

        public void Create(CmCompanyType data) {
            var persist2 = _context.CmCompanyType
            .Where(x => /*x.SiteId == data.SiteId && */x.Name == data.Name).FirstOrDefault();
            if (persist2 != null) {
                throw new ServiceException("이미 동일 이름이 존재합니다.");
            }

            _context.CmCompanyType.Add(data);
            _context.SaveChanges();
        }

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

            var persist2 = _context.CmCompanyType
            .Where(x => x.CompanyTypeId != id/* && x.SiteId == siteId*/ && x.Name == data.Name).FirstOrDefault();
            if (persist2 != null) {
                throw new ServiceException("이미 동일 이름이 존재합니다.");
            }

            //persist.SiteId = data.SiteId;
            persist.CompanyTypeId = data.CompanyTypeId;
            persist.Name = data.Name;
            persist.IsUse = data.IsUse;
            _context.CmCompanyType.Update(persist);
            _context.SaveChanges();
        }

        public void Delete(int id) {
            var data = _context.CmCompanyType.First(x => x.CompanyTypeId == id/* && x.SiteId == siteId*/);
            //data.IsUse = false;

            _context.CmCompanyType.Remove(data);
            _context.SaveChanges();
        }
    }
}