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

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

        public void Save(int siteId, int userGroupId, SitemapType type, SitemapAuth[] list) {
            // ID만 넘겼을경우 ID검증
            foreach (var data in list) {
                /*
                if (data.Sitemap == null)
                    data.Sitemap = _context.Sitemap.Single(x => x.SitemapId == data.SitemapId);
                if (data.UserGroup == null)
                    data.UserGroup = _context.CmUserGroup.Single(x => x.UserGroupId == data.UserGroupId);
                */
                data.Updated = DateTime.Now;
            }

            using (var tran = _context.Database.BeginTransaction()) {
                // 사용자그룹의 메뉴타입 전체제거
                var auths = _context.SitemapAuth.Where(x => x.SiteId == siteId && x.UserGroupId == userGroupId && x.SitemapType == type);
                _context.SitemapAuth.RemoveRange(auths);
                // 재등록
                _context.SitemapAuth.AddRange(list);
                _context.SaveChanges();
                tran.Commit();
            }
        }

        public SitemapAuth Get(Guid id) {
            var query = _context.SitemapAuth.Single(x => x.SitemapAuthId == id);
            return query;
        }

        public IQueryable<SitemapAuth> Gets(Guid id) {
            var query = _context.SitemapAuth.Where(x => x.SitemapAuthId == id);
            return query;
        }

        public IQueryable<Sitemap> SitemapAll() {
            var query = _context.Sitemap;
            return query;
        }

    }
}