using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Kreta.BusinessLogic.HelperClasses;
using Kreta.BusinessLogic.Interfaces;
using Kreta.Client.FileService.Request;
using Kreta.Core;
using Kreta.Core.ConnectionType;
using Kreta.Core.Logic;
using Kreta.DataAccess.Interfaces;
using Kreta.DataAccessManual;
using Kreta.Ellenorzo.Dao.VN.FeltoltottFajl;
using Kreta.Enums;

namespace Kreta.BusinessLogic.Helpers
{
    public class OpenBoardHelper : LogicBase
    {
        #region Fields

        private readonly IFileServiceHelper fileServiceHelper;

        #endregion Fields

        #region Constructors

        public OpenBoardHelper(IConnectionType connectionType, IFileServiceHelper fileServiceHelper) : base(connectionType)
        {
            this.fileServiceHelper = fileServiceHelper ?? throw new ArgumentNullException(nameof(fileServiceHelper));
        }

        public OpenBoardHelper(IConnectionType connectionType) : base(connectionType) { }

        #endregion Constructors

        /// INFO @MadachF: Mobil használja
        public DataSet FileKereses(FileKeresesRequestDao model)
        {
            return Dal.CustomConnection.Run(ConnectionType, (h) =>
            {
                var dal = h.DKT_FileDAL(GridParameters);
                return dal.FileKereses(IntezmenyId, TanevId, model, true);
            });
        }

        public List<OpenBoardFileCo> GetFiles(FileKeresesRequestDao model)
        {
            return Dal.CustomConnection.Run(ConnectionType, (h) =>
            {
                var dal = h.DKT_FileDAL(GridParameters);
                var fileDaos = dal.FileKereses(IntezmenyId, TanevId, model, false).ToDaoList<FileKeresesResponseDao>();
                var files = new List<OpenBoardFileCo>();

                foreach (var fileDao in fileDaos)
                {
                    var file = new OpenBoardFileCo(fileDao);
                    var fileName = string.Concat(file.Nev.TrimEnd('.'), '.', file.Kiterjesztes.TrimStart('.'));
                    var fileContent = fileServiceHelper.GetFile(IntezmenyAzonosito, new GetUrlRequest(file.Utvonal, file.Guid.Value, fileName))?.Tartalom;
                    if (!string.IsNullOrWhiteSpace(fileContent))
                    {
                        file.Content = Convert.FromBase64String(fileContent);
                        files.Add(file);
                    }
                }

                return files;
            });
        }

        public OpenBoardFileCo GetFile(int oraFileId)
        {
            return Dal.CustomConnection.Run(ConnectionType, (h) =>
            {
                var oraFileDal = h.OraFile();
                var oraFileEntity = oraFileDal.Get(oraFileId);

                return new OpenBoardFileCo(oraFileEntity);
            });
        }

        /// INFO @MadachF: Mobil használja
        public int GetFeltoltottFajlokSzama(DateTime feltoltesDatuma, int? orarendiOraId, int? tanitasiOraId)
        {
            return Dal.CustomConnection.Run(ConnectionType, (h) =>
            {
                var dal = h.DKT_FileDAL();
                var fajlokSzama = 0;

                if (tanitasiOraId.HasValue)
                {
                    ITanitasiOra tanitasiOra = h.TanitasiOra().Get(tanitasiOraId.Value);
                    fajlokSzama += dal.GetFeltoltottFajlokSzamaByOrarendiOraId(IntezmenyId, TanevId, feltoltesDatuma, tanitasiOra.OrarendiOraGroupId > 0 ? tanitasiOra.OrarendiOraGroupId.Value : 0);
                    fajlokSzama += dal.GetFeltoltottFajlokSzamaByTanitasiOraId(IntezmenyId, TanevId, tanitasiOraId.Value);
                }
                else
                {
                    fajlokSzama += dal.GetFeltoltottFajlokSzamaByOrarendiOraId(IntezmenyId, TanevId, feltoltesDatuma, orarendiOraId.Value);
                }

                return fajlokSzama;
            });
        }

        public string GetFeltoltottFajlokToTanuloOraAdat(DateTime datum, int? orarendiOraId, int? tanitasiOraId)
        {
            int cnt = 0;
            StringBuilder sb = new StringBuilder();

            if (orarendiOraId.HasValue || tanitasiOraId.HasValue)
            {
                Dal.CustomConnection.Run(ConnectionType, (h) =>
                {
                    if (tanitasiOraId.HasValue)
                    {
                        var entity = h.TanitasiOra().Get(tanitasiOraId.Value);
                        if (entity.OrarendiOraGroupId.IsEntityId())
                        {
                            orarendiOraId = h.TanitasiOra().GetOrarendiOraByTanoraGroupId(entity.OrarendiOraGroupId.Value, datum);
                        }
                    }

                    var fileKereses = new FileKeresesRequestDao
                    {
                        DatumTol = datum,
                        DatumIg = datum,
                        OrarendiOraId = orarendiOraId,
                        TanitasiOraId = tanitasiOraId,
                        OraFileTipusId = (int)OraFileTipusEnum.openboard
                    };

                    var files = GetFiles(fileKereses).Where(x => x.Lathato);

                    sb.Append(@"<h4 style=""padding-top:10px"">Órához kapcsolódó képek</h4>");

                    foreach (var file in files)
                    {
                        cnt++;

                        sb.AppendFormat(@"<p><span style=""font-size:small; text-decoration:underline;""><label onclick=""var newWindow = window.open('', '_blank'); newWindow.document.body.innerHTML = '<a href={0} download={1}.{2} target=_blank><img src={0}></a>'; "" onMouseOver=""this.style.cursor = 'pointer'"">{1}</label></span></p>", "data:image/jpeg;base64," + Convert.ToBase64String(file.Content), file.Nev, file.Kiterjesztes);
                    }
                });
            }
            return cnt > 0 ? sb.ToString() : "";
        }

        public void SaveOraFileData(int oraFileId, string fileNev, string megjegyzes)
        {
            Dal.CustomConnection.Run(ConnectionType, (h) =>
            {
                var oraFileDAL = h.OraFile();
                oraFileDAL.SaveOraFileData(oraFileId, fileNev, megjegyzes);
            });
        }
    }
}