using IntegraitonR3.Models;
using NLog;
using RnD.API;
using RnD.Attributes;
using RnD.Common.Enums;
using RnD.Common.Model.ActionBarButtons;
using RnD.CustomFunctionTypes;
using RnD.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using IntegraitonR3.Commands;
using System.Data.SqlClient;

namespace IntegraitonR3.RDnL.ActionBarButtons
{
    /// <summary>
    /// Integration R3 button class
    /// </summary>
    [CustomFunction("IntegrationR3CutomActionBar")]
    public class JsonGenerateRThree : AdvancedCustomFunction, ICustomActionBarButton
    {
        #region Constructors
        public JsonGenerateRThree(IAPI aAPI) : base(aAPI) { }
        #endregion

        #region Methods
        /// <summary>
        /// The method of clicking on the integration button
        /// </summary>
        /// <param name="aCustomisationObject">Custom object (expect Sample)</param>
        /// <returns>Result of integration</returns>
        public ActionBarButtonResult Execute(List<ICustomizationObject> aCustomisationObject)
        {
            var sampleEntity = aCustomisationObject.FirstOrDefault(c => c is ISample) as ISample;
            if (sampleEntity == null)
            {
                return new ActionBarButtonResult { Message = $"Объект не является пробой", MessageType = MessageType.Error };
            }
            var sample = API.Sample.GetSample(sampleEntity.ID);
            var passportLayoutTable = DatabaseContext.Database
                                     .SqlQuery<PassportLayoutTable>($"SELECT * FROM [RndSuite].[PasportLayoutTable] WHERE [SC] = @SampleId", new SqlParameter("@SampleId", sampleEntity.ID))
                                     .FirstOrDefault(c => c.languageName == "RUS");

            var passportMainTables = DatabaseContext.Database
                                    .SqlQuery<PasportMainTable>($"SELECT * FROM [RndSuite].[PasportMainTable] WHERE [SC] = @SampleId", new SqlParameter("@SampleId", sampleEntity.ID))
                                    .ToList();

            if (passportLayoutTable == null)
            {
                return new ActionBarButtonResult { Message = $"Не найденны данные паспорта качества по пробе {sample.ShortDescription}", MessageType = MessageType.Error };
            }
            decimal permLocation = 2; //Location of Perm
            if (passportLayoutTable.locationId != permLocation)
            {
                return new ActionBarButtonResult { Message = $"Локация паспорт качества не соответствует заданной", MessageType = MessageType.Error };
            }
            var logger = LogManager.GetCurrentClassLogger();
            try
            {
                R3 rThree = R3Commads.FillRThree(sample, passportLayoutTable, passportMainTables, DatabaseContext); //  RThree model formation
                if (rThree.Qualities.Count == 0)
                {
                    R3Commads.WriteSendStatus(sample, "Not filled in"); //Write send status to info field
                    return new ActionBarButtonResult { Message = "Отсутствуют передаваемые параметры.", MessageType = MessageType.Error };
                }
                #region Hardcode by technical task
                R3Commads.AddCountingPoint(ref rThree);
                R3Commads.AddSamplingPlace(ref rThree, passportLayoutTable.batchNumber);
                #endregion

                #region Send KSSH
                RndaAuthorization authData = R3Commads.GetAuthorizationData(DatabaseContext); // Get auth data for authorization on web api
                var message = R3Commads.SendPostRequestKssh(logger, rThree, authData, sample.ID);  //Send post request to KSSH
                #endregion

                //#region Test json serializtion
                //R3Commad.JsonSerialization(rThree); //Test serialization json on disk
                //#endregion

                R3Commads.WriteSendStatus(sample, message.Key); //Write send status to info field
                var messageType = message.Key == "Failed" ? MessageType.Error : MessageType.Information;
                return new ActionBarButtonResult { Message = message.Value, MessageType = messageType };
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return new ActionBarButtonResult { Message = $"Внутренняя ошибка программы, {ex.Message}", MessageType = MessageType.Error };
            }
        }

        /// <summary>
        /// Filling in button properties
        /// </summary>
        /// <returns>Button properties</returns>
        public ActionBarButtonMetadata GetActionBarButtonMetadata() =>
        new ActionBarButtonMetadata
        {
            Description = "Передать ПК в R3",
            Position = 5,
            IconClass = "icon-cmdJson24",
            DropdownIdentifier = "Экспорт ПК",
            IsVisibleWhen = new List<ActionBarButtonVisibility> { ActionBarButtonVisibility.Sample },
        };
        #endregion
    }
}
