using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.ApiKPI.Controllers
{
    public class ItemLayoutController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerKpiItem _sigerKpiitem;
        private readonly ISigerKpiItemDisplaySetting _kpiItemDisplaySetting;
        private readonly ISigerProjectSectionRepository _sigerProjectSection;
        private readonly ISigerKpiAuthority _kpiAuthority;

        public ItemLayoutController(IUnitOfWork unitOfWork, ISigerKpiItem sigerKpiItem,ISigerKpiItemDisplaySetting sigerKpiItemDisplay,ISigerProjectSectionRepository sigerProjectSection,ISigerKpiAuthority kpiAuthority)
        {
            _unitOfWork = unitOfWork;
            _sigerKpiitem = sigerKpiItem;
            _kpiItemDisplaySetting = sigerKpiItemDisplay;
            _sigerProjectSection = sigerProjectSection;
            _kpiAuthority = kpiAuthority;
        }
        [HttpGet]
        public IActionResult GetSetting(int section)
        {
            var data = _kpiItemDisplaySetting.Get(f => f.projectId == ProjectId && f.section == section);
            if (data==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            return new ObjectResult(data);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="layout"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestItemLayout layout)
        {
            var permission = _kpiAuthority.VerifyPermission(UserId, layout.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            var obj = _kpiItemDisplaySetting.Get(f => f.projectId == ProjectId && f.id==layout.Id);
            if (obj==null)
            {
                _kpiItemDisplaySetting.Insert(new Middlelayer.KpiRespository.Entities.SigerProjectKpiDisplaySetting {
                     projectId=ProjectId,
                     section=layout.Section,
                     col=layout.Col,
                     row=layout.Row,
                     status=(int)RowState.Valid
                });
            }
            else
            {
                obj.row = layout.Row;
                obj.col = layout.Col;
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
    }
}
