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

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

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

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

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

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

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

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

            //persist.SiteId = data.SiteId;
            persist.PositionId = data.PositionId;
            persist.Name = data.Name;
            persist.IsUse = data.IsUse;
            _context.CmPosition.Update(persist);
            _context.SaveChanges();
        }

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