using StructureHelperCommon.Infrastructures.Exceptions;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Loggers;
using StructureHelperLogics.Models.CrossSections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataAccess.DTOs
{
    public class VersionItemToDTOConvertStrategy : IConvertStrategy<ISaveable, ISaveable>
    {
        private const string AnalysisIs = "Analysis type is";
        private IConvertStrategy<CrossSectionDTO, ICrossSection> crossSectionConvertStrategy = new CrossSectionToDTOConvertStrategy();
        public Dictionary<(Guid id, Type type), ISaveable> ReferenceDictionary { get; set; }
        public IShiftTraceLogger TraceLogger { get; set; }


        public ISaveable Convert(ISaveable source)
        {
            try
            {
                Check();
                return GetNewAnalysis(source);
            }
            catch (Exception ex)
            {
                TraceLogger?.AddMessage(LoggerStrings.LogicType(this), TraceLogStatuses.Error);
                TraceLogger?.AddMessage(ex.Message, TraceLogStatuses.Error);
                throw;
            }
        }

        private ISaveable GetNewAnalysis(ISaveable source)
        {
            ISaveable newItem;
            if (source is ICrossSection crossSection)
            {
                newItem = ProcessCrossSection(crossSection);
            }
            else
            {
                string errorString = ErrorStrings.ObjectTypeIsUnknownObj(source);
                TraceLogger?.AddMessage(errorString, TraceLogStatuses.Error);
                throw new StructureHelperException(errorString);
            }
            return newItem;
        }

        private ISaveable ProcessCrossSection(ICrossSection crossSection)
        {
            TraceLogger?.AddMessage(AnalysisIs + " Cross-Section Ndm Analysis", TraceLogStatuses.Debug);
            ISaveable saveable;
            crossSectionConvertStrategy.ReferenceDictionary = ReferenceDictionary;
            crossSectionConvertStrategy.TraceLogger = TraceLogger;
            var convertLogic = new DictionaryConvertStrategy<CrossSectionDTO, ICrossSection>()
            {
                ReferenceDictionary = ReferenceDictionary,
                ConvertStrategy = crossSectionConvertStrategy,
                TraceLogger = TraceLogger
            };
            saveable = convertLogic.Convert(crossSection);
            return saveable;
        }

        private void Check()
        {
            var checkLogic = new CheckConvertLogic<ISaveable, ISaveable>(this);
            checkLogic.Check();
        }
    }
}
