using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Kreta.BusinessLogic.Classes;
using Kreta.BusinessLogic.HelperClasses;
using Kreta.BusinessLogic.Helpers;
using Kreta.BusinessLogic.Logic.TanuloErtekeles;
using Kreta.Enums;
using Kreta.Enums.ManualEnums;
using Kreta.Framework;
using Kreta.Framework.Entities;
using Kreta.Framework.Util;
using Kreta.Resources;
using Kreta.Web.Helpers;
using Kreta.Web.Helpers.Error;
using Kreta.Web.Security;

namespace Kreta.Web.Areas.TanuloErtekeles.ApiControllers
{
    public abstract class BaseTanuloErtekelesApiController : ApiController
    {

        protected DataSet GetDetailGridDataBase(int tanuloId, int? tantargyId, bool showToroltElemek, DateTime? datum, int ertekelesMegjelenesFajtaEnumId, int? feladatKategoriaId = null, int? oktatasiNevelesiFeladatId = null, bool isTanuloView = false, GridParameters gridParameters = null, bool isFromSzervezet = false)
        {

            var helper = new TanuloErtekelesHelper(ConnectionTypeExtensions.GetSessionConnectionType())
            {
                GridParameters = gridParameters
            };
            DataSet dataSet = helper.GetTanuloErtekelesDataSetForDetailGrid(
                tanuloId,
                tantargyId,
                showToroltElemek,
                isTanuloView,
                ClaimData.FelhasznaloId,
                ertekelesMegjelenesFajtaEnumId,
                datum,
                feladatKategoriaId,
                oktatasiNevelesiFeladatId,
                isFromSzervezet
            );

            return dataSet;
        }

        protected HttpResponseMessage SaveTanuloErtekelesList(HttpRequestMessage request, List<TanuloErtekelesCo> tanuloErtekelesCoList, int? szervezetTipusId = null)
        {
            var validator = new TanuloErtekelesValidacioWeb(ConnectionTypeExtensions.GetSessionConnectionType());

            validator.Validate(tanuloErtekelesCoList);

            ModelState.AddRange(new Dictionary<string, List<string>> { { "Error", validator.ErrorMessageList } });
            if (ModelState.IsValid)
            {
                try
                {
                    var helper = new TanuloErtekelesHelper(ConnectionTypeExtensions.GetSessionConnectionType());
                    helper.SaveTanuloErtekelesList(ClaimData.FelhasznaloId, tanuloErtekelesCoList, szervezetTipusId);
                }
                catch (KretaError ke)
                {
                    SDAServer.Instance.Logger.ExceptionThrown(ke);
                    ModelState.AddModelError("Error", ke.Message);
                }

                if (ModelState.IsValid)
                {
                    return new HttpResponseMessage(HttpStatusCode.OK);
                }
            }

            return request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }

        public HttpResponseMessage DeleteTanuloErtekeles(int id, bool isValid, int? szervezetTipusId = null)
        {
            if (!isValid)
            {
                throw new StatusError(HttpStatusCode.Forbidden, ErrorResource.AFelhasznalonakNincsMegfeleloJogosultsagaAFunkcioHasznalatahoz);
            }

            try
            {
                var helper = new TanuloErtekelesHelper(ConnectionTypeExtensions.GetSessionConnectionType());
                var naplozarasLogic = new NaplozarasLogic(ConnectionTypeExtensions.GetSessionConnectionType());
                var ertekelesCo = helper.GetTanuloErtekelesCoById(id);
                if (ertekelesCo.OsztalyCsoportId.HasValue && naplozarasLogic.GetLezartOsztalyokEsBontottCsoportjaik().Contains(ertekelesCo.OsztalyCsoportId.Value))
                {
                    throw new StatusError(HttpStatusCode.BadRequest, TanuloErtekelesResource.AKivalasztottOsztalyNaplojaLezartNemTorolhetErtekelestAzOsztalyTanuloinaknak);
                }

                helper.DeleteTanuloErtekelesById(id, szervezetTipusId);

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (EntityDeleteFailedException)
            {
                throw new StatusError(HttpStatusCode.BadRequest, string.Format(StringResourcesUtil.GetString(5490), StringResourcesUtil.GetString(168)) /*A(z) Értékelés nem törölhető, mert egy vagy több kapcsolódása van (kapcsolatok: {1})!*/);
            }
            catch (Exception e)
            {
                throw new StatusError(HttpStatusCode.InternalServerError, StringResourcesUtil.GetString(4358) /*Hiba történt törlés közben!*/)
                {
                    UnHandledException = e
                };
            }
        }

        protected bool IsTanitasiNap(DateTime date, int? osztalycsoportId)
        {
            DateTime sqlMinDate = SqlDateTime.MinValue.Value.Date;
            DateTime sqlMaxDate = SqlDateTime.MaxValue.Value.Date;
            if (date < sqlMinDate || date > sqlMaxDate)
            {
                throw new OverflowException(string.Format(ErrorResource.ADatumNemLehetKisebbMintVagyNagyobbMint, sqlMinDate.ToShortDateString(), sqlMaxDate.ToShortDateString()));
            }

            var helper = new TanevrendHelper(ConnectionTypeExtensions.GetSessionConnectionType());

            var osztalyTanevrendjei = helper.GetOsztalycsoportTanevrendje(date, osztalycsoportId ?? 0);
            if (osztalyTanevrendjei.Any(x => x.Naptipus == (int)NapTipusEnum.vizsganap))
            {
                return true;
            }

            bool result = helper.IsTanitasiNap(date, osztalycsoportId);
            return result;
        }
    }
}