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

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

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

        public IQueryable<CmBusinessField> Gets(int id) {
            var data = _context.CmBusinessField.Where(x => x.BusinessFieldId == id);
            return data;
        }

        public void Create(CmBusinessField data) {
            var persist2 = _context.CmBusinessField
            .Where(x => x.Name == data.Name).FirstOrDefault();
            if (persist2 != null) {
                throw new ServiceException("이미 동일한 정보가 존재합니다.");
            }

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

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

            var persist2 = _context.CmBusinessField
            .Where(x => x.BusinessFieldId != id && x.Name == data.Name).FirstOrDefault();
            if (persist2 != null) {
                throw new ServiceException("이미 동일한 정보가 존재합니다.");
            }

            persist.BusinessFieldId = data.BusinessFieldId;
            persist.Name = data.Name;
            persist.IsUse = data.IsUse;
            _context.CmBusinessField.Update(persist);
            _context.SaveChanges();
        }

        public void Delete(int id) {
            var data = _context.CmBusinessField.First(x => x.BusinessFieldId == id);
            _context.CmBusinessField.Remove(data);
            _context.SaveChanges();
        }
    }
}