using System;
using System.Data;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using Kreta.BusinessLogic.Exceptions;
using Kreta.BusinessLogic.Helpers;
using Kreta.BusinessLogic.Security;
using Kreta.BusinessLogic.Utils;
using Kreta.Core;
using Kreta.Core.Exceptions;
using Kreta.Core.FeatureToggle;
using Kreta.Enums.ManualEnums;
using Kreta.Resources;
using Kreta.Web.Areas.Adminisztracio.Models;
using Kreta.Web.Classes;
using Kreta.Web.Helpers;
using Kreta.Web.Helpers.Error;
using Kreta.Web.Helpers.Grid;
using Kreta.Web.Models.EditorTemplates;
using Kreta.Web.Security;

namespace Kreta.Web.Areas.Adminisztracio.Controllers
{
    [MvcRoleClaimsAuthorize(true)]
    [MvcRolePackageDenyAuthorize(KretaClaimPackages.IsOnlyAlkalmozott.ClaimValue)]
    [MvcRolePackageAuthorize(TanevEnum.AktEsKovTanev, KretaClaimPackages.Adminisztrator.ClaimValue)]
    public class KIRTanuloImportController : Controller
    {
        private IFeatureContext FeatureContext { get; }

        private IUploadFileValidator UploadFileValidator { get; }

        public KIRTanuloImportController(IFeatureContext featureContext, IUploadFileValidator uploadFileValidator)
        {
            FeatureContext = featureContext ?? throw new ArgumentNullException(nameof(featureContext));
            UploadFileValidator = uploadFileValidator ?? throw new ArgumentNullException(nameof(uploadFileValidator));
        }

        // GET: Adminisztracio/KIRTanuloImport
        public ActionResult Index()
        {
            var model = new TanuloKIRImportModel
            {
                KirLoginModel = new KIRLoginModel()
                {
                    OmAzonosito = ClaimData.OrganizationCode,
                },
                TanevId = ClaimData.SelectedTanevID.Value,
                KIRImportEnabled = FeatureContext.IsEnabled(Core.Constants.FeatureName.KIRImport),
                MaxAllowedFileSizeInBytes = UploadFileValidator.Configuration.ImportMaxAllowedFileSizeInBytes,
                AllowedFileExtensions = UploadFileValidator.Configuration.ImportAllowedFileExtensions,
                IsSzakkepzoIntezmeny = ClaimData.IsSzakkepzoIntezmeny,
            };

            return View(model);
        }

        public ActionResult OpenKIRTanuloImportPopup(TanuloKIRImportModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var kirHelper = new KirHelper(ConnectionTypeExtensions.GetSessionConnectionType(), model.KirLoginModel.OmAzonosito, model.KirLoginModel.FelhasznaloNev, jelszo: model.KirLoginModel.Jelszo);
                    var tanarestanuloKirImportModel = new TanuloKIRImportModel
                    {
                        TanevId = ClaimData.SelectedTanevID.Value,
                        KIRImportModel = new KIRImportModel
                        {
                            OmAzonosito = model.KirLoginModel.OmAzonosito,
                            FelhasznaloNev = model.KirLoginModel.FelhasznaloNev,
                            KirToken = kirHelper.KirToken,
                            TelephelyList = kirHelper.GetTelephelyList().ToSelectListItemList()
                        },
                        KirLoginModel = new KIRLoginModel
                        {
                            OmAzonosito = model.KirLoginModel.OmAzonosito,
                            FelhasznaloNev = model.KirLoginModel.FelhasznaloNev
                        },
                    };

                    var pm = new PopUpModel(tanarestanuloKirImportModel, "KIRTanuloImportModal");
                    pm.AddCancelBtn(pm, "KretaWindowHelper.destroyAllWindow");
                    pm.AddBtn(pm, "BtnKIRImport", 3486 /*Importálás*/, "KIRTanuloImportHelper.KIRImport");

                    return PartialView(Constants.General.PopupView, pm);
                }
                catch (Exception e)
                {
                    StatusError error = new StatusError(HttpStatusCode.BadRequest, e.Message);
                    throw error;
                }
            }

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        public ActionResult KIRImport(TanuloKIRImportModel model)
        {
            if (ModelState.IsValid)
            {
                var kirHelper = new KirHelper(ConnectionTypeExtensions.GetSessionConnectionType(), model.KIRImportModel.OmAzonosito, model.KIRImportModel.FelhasznaloNev, kirToken: model.KIRImportModel.KirToken);

                var tanuloList = kirHelper.GetTanuloList(model.KIRImportModel.TelephelyKod.Value);

                LicenceHelper.LicenceWait(ClaimData.LicenceDatum);

                var anotherYearId = Kreta.Web.Classes.Utils.GetAnotherYearId();
                new EgysegesImportHelper(ConnectionTypeExtensions.GetActiveSessionConnectionType()).ExecuteKIRTanuloImport(tanuloList, anotherYearId, ClaimData.IsKovTanev);
            }

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }

        public ActionResult OpenTanuloImportPopUp(bool? isJuttatasUpdate)
        {
            var helper = new EgysegesImportHelper(ConnectionTypeExtensions.GetActiveSessionConnectionType());

            var tanulokFelolteseModel = new TanulokFeltolteseModel
            {
                TanevId = ClaimData.SelectedTanevID.Value,
                Errors = helper.TanuloKIRAdatok.Validate(),
                IsJuttatasUpdate = isJuttatasUpdate,
                IsSzakkepzoIntezmeny = ClaimData.IsSzakkepzoIntezmeny,
            };

            var model = new PopUpModel(tanulokFelolteseModel, "TanulokFeltolteseModal");
            model.AddCancelBtn(model, "KretaWindowHelper.destroyAllWindow");

            if (tanulokFelolteseModel.Errors.Count == 0)
            {
                model.AddOkBtn(model, "KIRTanuloFeltoltesHelper.Save");
            }

            return PartialView(Constants.General.PopupView, model);
        }

        public ActionResult UploadKIRTanuloFile(HttpPostedFileBase importTanuloFile)
        {
            UploadFileValidator.ValidateImportFile(importTanuloFile);

            try
            {
                TantervHelper helper = new TantervHelper(ConnectionTypeExtensions.GetSessionConnectionType());

                DataSet tantervDataSet = helper.TantervKereses();
                if (!tantervDataSet.Tables[0].Rows.Count.IsNotNullAndPositive())
                {
                    throw new BlException(ImportExportOrarendResource.TantervNotFound);
                }

                LicenceHelper.LicenceWait(ClaimData.LicenceDatum);

                var anotherYearId = Kreta.Web.Classes.Utils.GetAnotherYearId();
                new EgysegesImportHelper(ConnectionTypeExtensions.GetSessionConnectionType()).ExecuteKIRTanuloImportFile(importTanuloFile.ContentLength, importTanuloFile.InputStream, importTanuloFile.FileName, anotherYearId, ClaimData.IsKovTanev, ClaimData.IsSzakkepzoIntezmeny);
            }
            catch (BlException e)
            {
                throw new StatusError(HttpStatusCode.BadRequest, e.Message);
            }
            catch (InvalidDataException e)
            {
                throw new StatusError(HttpStatusCode.BadRequest, e.Message);
            }
            catch (KretaInvalidFileFormatException e)
            {
                throw new StatusError(HttpStatusCode.BadRequest, e.Message);
            }
            catch (Exception e)
            {
                throw new StatusError(HttpStatusCode.BadRequest, e.Message);
            }

            return Content(string.Empty);
        }

        public ActionResult SaveTanulok(bool? isJuttatasUpdate)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var helper = new EgysegesImportHelper(ConnectionTypeExtensions.GetSessionConnectionType());

                    LicenceHelper.LicenceWait(ClaimData.LicenceDatum);
                    helper.SaveImportaltTanulok(isJuttatasUpdate ?? false);

                    return Json(new { tovabbUrl = @"/Tanulo/Tanulo" });
                }
                catch (BlException)
                {
                    throw;
                }
                catch (SDA.DataProvider.UniqueKeyViolationException)
                {
                    /*A fájlban szereplő oktatási azonosítóval már szerepel diák az adatbázisban*/
                    StatusError error = new StatusError(HttpStatusCode.BadRequest, StringResourcesUtils.GetString(4852));
                    throw error;
                }
            }

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        public ActionResult GetPreLoadedStudents(DataSourceRequest request)
        {
            var helper = new EgysegesImportHelper(ConnectionTypeExtensions.GetActiveSessionConnectionType());

            helper.GridParameters = Converter.GridParameter(request);
            return Json(helper.GetImportaltTanulok().ToDataSourceResult(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult DownloadTemplate()
        {
            string filePath = Kreta.Web.Classes.Utils.GetExcelTemplateFilePath(Constants.ImportExport.TanuloImportSablonNev);

            if (filePath == null)
            {
                throw new StatusError(HttpStatusCode.BadRequest, ErrorResource.FajlNemLetezik);
            }

            return File(filePath, Core.Constants.ContentTypes.Xlsx, Constants.ImportExport.TanuloImportSablonNev);
        }

        public ActionResult ExportAktualisAdatok()
        {
            var memoryStream = new EgysegesImportHelper(ConnectionTypeExtensions.GetSessionConnectionType()).ExportTanuloAktualisAdatok();
            return new FileStreamResult(memoryStream, Core.Constants.ContentTypes.Xlsx) { FileDownloadName = $"{TanuloResource.TanulokExport}.{Constants.ImportExport.FileFormatXlsx}" };
        }
    }
}