using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Kendo.Mvc.UI;
using Kreta.BusinessLogic.Helpers;
using Kreta.BusinessLogic.Interfaces;
using Kreta.BusinessLogic.Logic;
using Kreta.BusinessLogic.Security;
using Kreta.BusinessLogic.Utils;
using Kreta.Core;
using Kreta.Framework.Util;
using Kreta.Resources;
using Kreta.Web.Areas.Tanar.Models;
using Kreta.Web.Helpers;
using Kreta.Web.Helpers.Error;
using Kreta.Web.Helpers.Grid;
using Kreta.Web.Security;
using Newtonsoft.Json;

namespace Kreta.Web.Areas.Tanar.ApiControllers
{
    [ApiRoleClaimsAuthorize(true)]
    [ApiRolePackageAuthorize(KretaClaimPackages.Adminisztrator.ClaimValue, KretaClaimPackages.Tanar.ClaimValue)]
    public class HaziFeladatCsatolmanyokApiController : ApiController
    {
        private readonly IFileServiceHelper fileServiceHelper;

        public HaziFeladatCsatolmanyokApiController(IFileServiceHelper fileServiceHelper)
        {
            this.fileServiceHelper = fileServiceHelper ?? throw new ArgumentNullException(nameof(fileServiceHelper));
        }

        public DataSourceResult GetHFCsatolmanyokGrid(string data, DataSourceRequest request)
        {
            var (gridParameter, modelList) = GetGridData(data, request);

            return modelList.ToDataSourceResult(gridParameter);
        }

        public HttpResponseMessage GetExport(string data, DataSourceRequest request)
        {
            try
            {
                var (gridParameter, modelList) = GetGridData(data, request);

                modelList = modelList.SortingAndPaging(gridParameter.OrderDictionary);

                var simpleExportColumnCos = SimpleExportLogic.GetSimpleExportColumnCos<HFCsatolmanyGridModel>(HFCsatolmanyGridModel.HazifeladatCsatolmanyExportAttributeId);

                var memoryStream = SimpleExportLogic.GetExport(OrarendResource.HazifeladatExportSheetName, simpleExportColumnCos, modelList, ClaimData.SelectedTanevID.Value);

                return HttpResponseExtensions.GetFileHttpResponse(memoryStream.ToArray(), OrarendResource.HazifeladatCsatolmanyExportFileName);
            }
            catch (Exception ex)
            {
                throw new StatusError(HttpStatusCode.BadRequest, ErrorResource.HibaTortentAFajlExportalasaKozben) { UnHandledException = ex };
            }
        }

        private (GridParameters gridParameter, List<HFCsatolmanyGridModel> modelList) GetGridData(string data, DataSourceRequest request)
        {
            data = data.Replace("-", "");

            var model = JsonConvert.DeserializeObject<HFCsatolmanyokSearchModel>(data) ?? new HFCsatolmanyokSearchModel();

            var gridParameter = Converter.GridParameter(request);

            var tanarId = ClaimData.IsAdministrator ? (int?)null : ClaimData.FelhasznaloId;

            var coList = new DktFileHelper(ConnectionTypeExtensions.GetSessionConnectionType()).GetHazifeladatCsatolmanyCoList(model.ConvertModelToCo(tanarId));

            var modelList = new List<HFCsatolmanyGridModel>();
            foreach (var co in coList)
            {
                var gridModel = new HFCsatolmanyGridModel(co);
                modelList.Add(gridModel);
            }

            return (gridParameter, modelList);
        }

        public DataSourceResult GetHFCsatolmanyokGridForHazi(int haziFeladatId, [ModelBinder(typeof(ModelBinder.DataSourceRequestModelBinder))] DataSourceRequest request)
        {
            var helper = new DktFileHelper(ConnectionTypeExtensions.GetSessionConnectionType())
            {
                GridParameters = Converter.GridParameter(request)
            };

            DataSet ds = helper.GetCsatolmanyokForHaziFeladatDataSet(haziFeladatId);
            return ds.ToDataSourceResult();
        }

        [HttpPost]
        [ApiValidateAjaxAntiForgeryToken]
        public HttpResponseMessage DeleteCsatolmany([FromBody] int id)
        {
            try
            {
                var helper = new DktFileHelper(ConnectionTypeExtensions.GetSessionConnectionType(), fileServiceHelper);
                helper.DeleteCsatolmany(id, true);

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                throw new StatusError(HttpStatusCode.BadRequest, ErrorResource.FajlTorleseSikertelen) { UnHandledException = ex };
            }
        }

        [HttpPost]
        [ApiValidateAjaxAntiForgeryToken]
        public HttpResponseMessage DeleteSelectedCsatolmany(List<int> idList)
        {
            try
            {
                var helper = new DktFileHelper(ConnectionTypeExtensions.GetSessionConnectionType(), fileServiceHelper);

                foreach (var item in idList)
                {
                    helper.DeleteCsatolmany(item, true);
                }

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                throw new StatusError(HttpStatusCode.BadRequest, ErrorResource.FajlokTorleseSikertelen) { UnHandledException = ex };
            }
        }

        [HttpPost]
        [ApiRolePackageAuthorize(KretaClaimPackages.Adminisztrator.ClaimValue, KretaClaimPackages.Tanar.ClaimValue, KretaClaimPackages.Tanulo.ClaimValue)]
        public HttpResponseMessage DownloadCsatolmanyFile(DownloadModel model)
        {
            try
            {
                var helper = new DktFileHelper(ConnectionTypeExtensions.GetSessionConnectionType(), fileServiceHelper);
                var co = helper.GetCsatolmanyFile(model.Id);

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(co.Stream);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = co.FileName;
                return response;
            }
            catch (Exception ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(@"
<!DOCTYPE html>
<html lang=""hu"">
<head>
<meta charset=""utf-8"" />
<meta name=""format-detection"" content=""telephone=no"" />
<meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" />
<meta http-equiv=""X-UA-Compatible"" content =""IE=Edge"" />
<title>Hiba file letöltés során!</title>
<link rel=""preconnect"" href=""https://fonts.googleapis.com"" crossorigin>
<link rel=""preconnect"" href=""https://fonts.gstatic.com"" crossorigin>
<link href=""https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400;1,600&family=Roboto+Condensed:wght@300;400;700&display=swap"" rel=""stylesheet"">
<link rel=""icon"" href=""~/favicon.ico"" type=""image/x-icon"">
<style>
        html {
            height: 100%;
        }

        body {
            margin: 0;
            padding: 0;
            height: 100%;
            font-family: ""Open Sans"";
            font-size: 14px;
            font-weight: 400;
            color: #445261;
            background: #406a7c; /* For browsers that do not support gradients */
            background: -webkit-radial-gradient(circle, #518094, #406a7c); /* Safari */
            background: -o-radial-gradient(circle, #518094, #406a7c); /* Opera 11.6 to 12.0 */
            background: -moz-radial-gradient(circle, #518094, #406a7c); /* Firefox 3.6 to 15 */
            background: radial-gradient(circle, #518094, #406a7c); /* Standard syntax */
        }

# main {
        height: 100 %;
        top: 0;
        position: absolute;
        width: 100 %;           
            background-repeat: no-repeat;
            background-position: bottom right 30px;
        }
#main h2 {
                color: white;
                font-weight: 400;
                font-size: 2em;
            }
#main .login_logo {
                margin: 0 auto;
                margin-top: 10%;
                width: 400px;
                display: block;
                background-position: center center;
                background-repeat: no-repeat;
                height: 100px;
                padding-top: 25px;
            }
#main .login_container {
                width: 40%;
                margin: 0 auto;
                display: block;
                background-color: transparent;
            }

            #main .login_problems {
                width: 100%;
                margin: 0 auto;
                display: block;
                background-color: transparent;
                line-height: 30px;
                color: white;
            }

            #main .login_header {
                background-color: transparent;
                text-align: center;
                margin-top: 40px;
            }

            #main .login_content {
                text-align: center;
                padding: 20px;
                -moz-box-sizing: border-box;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
                overflow-y: auto;
                color: white;
                font-size: 18px;
                font-weight: 300;
            }
    </style>
</head>
<body>
    <div id = ""main"" >
        <div class=""login_logo"">
        </div>

        <div class=""login_container"">
            <div class=""login_header"">
                <h2>Hiba történt a file letöltése során!</h2>
            </div>
        </div>

        <div class=""login_problems"">
            <div class=""login_content"">
                A file service nem elérhető jelenleg vagy a letölteni kívánt filet már törölték.
            </div>
        </div>
    </div>
</body>
</html>
");
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return response;
            }
        }

        [HttpGet]
        public Dictionary<string, string> GetFelhasznaloAdatmennyisege(int felhasznaloId)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            var dktFileHelper = new DktFileHelper(ConnectionTypeExtensions.GetSessionConnectionType());
            var osszMeret = dktFileHelper.GetHaziFeladatCsatolmanyokOsszMeret(felhasznaloId);
            var maxMegengedettAdatmennyiseg = dktFileHelper.GetMaxAdatmennyisegFelhasznalokent(felhasznaloId);

            var marFeltoltottAdatmennyisegInMB = string.Format("{0:0.00}", CommonUtils.ConvertByteToMByte(osszMeret)); // DB-ben byte van
            var maxAdatmennyisegInMB = string.Format("{0:0.00}", CommonUtils.ConvertKByteToGByte(maxMegengedettAdatmennyiseg)); // DB-ben kByte van

            result.Add("marFeltoltottAdatmennyiseg", ClaimData.IsAdministrator ? string.Format(TanarResource.MarFeltoltottAdatmennyiseg, marFeltoltottAdatmennyisegInMB) : string.Format(TanarResource.KorabbanMarFeltoltottAdatmennyiseg, marFeltoltottAdatmennyisegInMB));
            result.Add("maxAdatmennyiseg", ClaimData.IsAdministrator ? string.Format(TanarResource.FelhasznalokentMaxAdatmennyiseg, maxAdatmennyisegInMB) : string.Format(TanarResource.MaximalisMegengedettAdatmennyiseg, maxAdatmennyisegInMB));

            return result;
        }
    }
}