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;
using System.Transactions;

namespace FMSApp.Repositories {
    public class WorkOrderRepository {
        private readonly ILogger<WorkOrderRepository> _logger;
        private readonly FMSContext _context;

        private readonly AppSettings _appSettings;
        private readonly StorageHelper _storage;

        public WorkOrderRepository(
            ILogger<WorkOrderRepository> logger,
            FMSContext context,
            IOptions<AppSettings> appSettings,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _appSettings = appSettings.Value;
            _storage = storage;
        }

        // 자동지시 처리
        public void CreateFromWorkRequests() {

            var today = DateTime.Now.Date;

            using (var trans = new TransactionScope()) {
                // 자동지시인것 중 당일 포함 이전작업일인 요청 자동생성
                var query = from schedule in _context.FmsWorkSchedule
                            join request in _context.FmsWorkRequest
                            on schedule.WorkScheduleId equals request.WorkScheduleId
                            where schedule.IsUse == true
                            && schedule.IsAutoOrder == true
                            && request.StartWorkDate <= today
                            && _context.FmsWorkOrder.Where(
                                order => order.SiteId == request.SiteId
                                && order.WorkRequestId == request.WorkRequestId
                                && order.Title == request.Title
                            ).Any() == false
                            select request;

                foreach (var request in query) {
                    CreateFromWorkRequest(request);
                }

                trans.Complete();
            }
        }

        public void CreateFromWorkRequest(FmsWorkRequest request, bool bTran = false) {
            TransactionScope trans = null;
            if (bTran) trans = new TransactionScope();
            try {
                // Request Update
                request.WorkProgressId = 2; // 작업대기
                _context.FmsWorkRequest.Update(request);
                _context.SaveChanges();

                // Order 및 OrderToFacility 생성
                var order = new FmsWorkOrder();

                foreach (var facility in request.FmsWorkSchedule.FmsWorkScheduleToFacility) {
                    order.FmsWorkOrderToFacility.Add(new FmsWorkOrderToFacility() {
                        SiteId = facility.SiteId,
                        FacilityCode = facility.FacilityCode
                    });
                }

                _context.FmsWorkOrder.Add(order);
                _context.SaveChanges();

                if (trans != null) trans.Complete();
            } finally {
                if (trans != null) trans.Dispose();
            }
        }
    }
}