using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using YGNT.QuestionLibrary.Core;
using YGNT.QuestionLibrary.Core.BaseData;
using YGNT.QuestionLibrary.Core.BaseData.PaperStructureSettingParam;

namespace YGNT.QuestionLibrary.EntityFrameworkCore.Seed
{
    public class DefaultPaperStructureSettingCreator
    {
        private readonly QuestionLibraryDbContext _context;

        /// <summary>
        /// name ,code ,isDefault
        /// </summary>
        private readonly object[,] _settings =
        {
            {"分卷" ,PaperStructureSettingConsts.分卷,"0",new Subsection()},
            {"装订线" ,PaperStructureSettingConsts.装订线,"0",new Gutter()},
            {"主标题",PaperStructureSettingConsts.主标题,"1",new MainTitle()},
            {"副标题",PaperStructureSettingConsts.副标题,"0",new SubTitle()},
            {"考试信息栏",PaperStructureSettingConsts.考试信息栏,"0",new TestInformationBar()},
            {"考生信息栏",PaperStructureSettingConsts.考生信息栏,"1",new CandidateInformationBar()},
            {"答题卡",PaperStructureSettingConsts.答题卡,"1",new AnswerSheet()},
            {"注意事项",PaperStructureSettingConsts.注意事项,"0",new AttentionNotice()},
            {"题型标题",PaperStructureSettingConsts.题型标题,"1",new List<QuestionTypeTitle>(){new QuestionTypeTitle()} },
        };

        public DefaultPaperStructureSettingCreator(QuestionLibraryDbContext context)
        {
            _context = context;
        }

        public void Create()
        {
            for (int i = 0; i < _settings.GetLength(0); i++)
            {
                var structureSetting = new PaperStructureSetting()
                {
                    Name = _settings[i, 0].ToString(),
                    Code = _settings[i, 1].ToString(),
                    IsDefault = _settings[i, 2].ToString() == "1",
                    Param = JsonConvert.SerializeObject(_settings[i, 3])
                };
                var setting = _context.PaperStructureSettings.FirstOrDefault(x => x.Code == structureSetting.Code);
                if (setting == null)
                {
                    _context.PaperStructureSettings.Add(structureSetting);
                    _context.SaveChanges();
                }
                else
                {
                    if (setting.Param != structureSetting.Param)
                    {
                        setting.Param = structureSetting.Param;
                        _context.Update(setting);
                        _context.SaveChanges();
                    }
                }
            }
        }
    }
}