using System.Collections.Generic;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class SigerProjectParameterRepository : ApiConfigRepositoryBase<siger_project_parameter>, ISigerProjectParameterRepository
    {
        private readonly ApiConfigDbContext _context;
        public SigerProjectParameterRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public bool AddParameter(string name, string module, string type, string unit, string category, string code, IEnumerable<RequestKeyValue> selectValue,
            int projectId, string description)
        {
            var entity = new siger_project_parameter
            {
                project_id = projectId,
                category = category,
                code = string.IsNullOrWhiteSpace(code) ? "" : code,
                module = module,
                name = name,
                unit = unit,
                type = type.ToInt(),
                description = description ?? ""
            };
            _context.siger_project_parameter.Add(entity);
            if (_context.SaveChanges() <= 0)
            {
                return false;
            }

            if (entity.type == 2)
            {
                var extends = new List<siger_project_parameter_extend>();
                foreach (var selected in selectValue)
                {
                    var extend = new siger_project_parameter_extend
                    {
                        project_id = projectId,
                        parameter_id = entity.id,
                        key = selected.key,
                        value = selected.value
                    };
                    extends.Add(extend);
                }
                _context.siger_project_parameter_extend.AddRange(extends);
                if (_context.SaveChanges() <= 0)
                {
                    return false;
                }
            }

            return true;
        }
    }
}
