using AutoMapper;
using Model.Models;
using System;
using UIShare.UIViewModel;

namespace ACP.Profiles
{
    /// <summary>
    /// UIShare.UIViewModel ↔ Model.Models 双向映射配置。
    /// </summary>
    public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            // ===== Parameter =====
            // ParameterModel.Type(System.Type) ↔ Parameter.TypeName(string)
            // ParameterModel.Category(enum) ↔ Parameter.Category(string)
            CreateMap<ParameterVM, Parameter>()
                .ForMember(dest => dest.TypeName,
                    opt => opt.MapFrom(src => src.Type != null ? src.Type.AssemblyQualifiedName : null))
                .ForMember(dest => dest.Category,
                    opt => opt.MapFrom(src => src.Category.ToString()));

            CreateMap<Parameter, ParameterVM>()
                .ForMember(dest => dest.Type,
                    opt => opt.MapFrom(src => string.IsNullOrEmpty(src.TypeName)
                        ? typeof(string)
                        : (Type.GetType(src.TypeName) ?? typeof(string))))
                .ForMember(dest => dest.Category,
                    opt => opt.MapFrom(src => ParseCategory(src.Category)));

            // ===== Step =====
            CreateMap<StepVM, Step>().ReverseMap();

            // ===== Program =====
            CreateMap<ProgramVM, Program>().ReverseMap();

            // ===== Method =====
            CreateMap<MethodVM, Method>().ReverseMap();

            // ===== DeviceInfo =====
            CreateMap<DeviceInfoVM, DeviceInfo>().ReverseMap();

            // ===== CanMessageShow =====
            CreateMap<CanMessageShowVM, CanMessageShow>().ReverseMap();


            // ===== InstructionNode =====
            CreateMap<InstructionNodeVM, InstructionNode>().ReverseMap();

            // ===== SubProgramItem =====
            CreateMap<SubProgramItemVM,SubProgramItem>().ReverseMap();
        }

        private static ParameterVM.ParameterCategory ParseCategory(string? category)
        {
            if (string.IsNullOrEmpty(category))
                return ParameterVM.ParameterCategory.Temp;
            return Enum.TryParse<ParameterVM.ParameterCategory>(category, true, out var result)
                ? result
                : ParameterVM.ParameterCategory.Temp;
        }
    }
}
