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

namespace FMSAdmin.Services {
    public class FormulaService {
        private readonly ILogger<FormulaService> _logger;
        private readonly FMSContext _context;

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


        public void Save(BemsFormula data) {
            using (var trans = new TransactionScope()) {

                data.Formula = data.Formula.ToUpper();

                var persist = _context.BemsFormula
                                .Where(x => x.SiteId == data.SiteId && x.FacilityTypeId == data.FacilityTypeId && x.FacilityCode == data.FacilityCode && x.FormulaId == data.FormulaId).FirstOrDefault();

                if (persist == null) {
                    _context.BemsFormula.Add(data);
                    _context.SaveChanges();
                } else {
                    persist.Formula = data.Formula;


                    if (persist.BemsFormulaParameter != null) {

                        foreach (var parm in persist.BemsFormulaParameter.ToList()) {
                            _context.BemsFormulaParameter.Remove(parm);
                        }
                        _context.SaveChanges();
                    }

                    foreach (var formulaParameterInfo in data.BemsFormulaParameter) {
                        persist.BemsFormulaParameter.Add(new BemsFormulaParameter() {
                            SiteId = persist.SiteId,
                            FacilityTypeId = persist.FacilityTypeId,
                            FacilityCode = persist.FacilityCode,
                            FormulaId = persist.FormulaId,
                            ParameterId = formulaParameterInfo.ParameterId,
                            ParameterFacilityCode = formulaParameterInfo.ParameterFacilityCode,
                            ParameterPropertyId = formulaParameterInfo.ParameterPropertyId

                        });
                    }

                    _context.BemsFormula.Update(persist);
                    _context.SaveChanges();
                }
                trans.Complete();
            }
        }


    }
}