using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiConfig.Controller
{
    public class LineStorageController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectLineStorageRepository _lineStorageRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        public LineStorageController(IUnitOfWork unitOfWork, ISigerProjectLineStorageRepository lineStorageRepository,
            ISigerProjectLevelSectionRepository levelSectionRepository,
            ISigerProjectLevelRepository levelRepository)
        {
            _unitOfWork = unitOfWork;
            _lineStorageRepository = lineStorageRepository;
            _levelSectionRepository = levelSectionRepository;
            _levelRepository = levelRepository;
        }

        [HttpGet]
        public IActionResult GetLineSectionTree()
        {
            var response = new List<LevelSectionTree>();

            var list = _levelSectionRepository.GetLevelSectionTree(ProjectId);

            var levels = _levelRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid);
            var maxLevelId = levels.OrderBy(q => q.levelid).Select(m => m.id).Max(q => q);

            foreach (var levelSectionTree in list)
            {
                if (levelSectionTree.levelId != maxLevelId)
                {
                    response.Add(levelSectionTree);
                }
            }

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetPagedLineStorage(int sectionId, string name, int page = 1, int pagesize = 10)
        {
            var response = _lineStorageRepository.GetPagedList(sectionId, name, ProjectId, page, pagesize);

            return new PagedObjectResult(response.Data, response.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddLineStorage([FromBody]RequestAddLineStorage request)
        {
            var isExist = _lineStorageRepository.IsExist(q =>
                q.project_id == ProjectId && q.storage_code == request.code && q.status == (int) RowState.Valid);
            if (isExist)
            {
                throw new BadRequestException(RequestEnum.ToolStorageNoIsExist);
            }

            if (string.IsNullOrEmpty(request.code) || string.IsNullOrEmpty(request.name) || string.IsNullOrEmpty(request.ipaddress) ||
                string.IsNullOrEmpty(request.print_category))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var entity = new siger_project_line_storage
            {
                section_id = request.sectionId,
                storage_code = request.code.Trim(),
                storage_name = request.name,
                project_id = ProjectId,
                ipaddress = request.ipaddress,
                macaddress = request.macaddress,
                com_port = request.com_port.ToInt(),
                print_category = request.print_category.ToInt(),
                print_port = request.print_port
            };
            _lineStorageRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditLineStorage([FromBody]RequestEditLineStorage request)
        {
            var isExist = _lineStorageRepository.IsExist(q =>
                q.project_id == ProjectId && q.storage_code == request.code && q.status == (int)RowState.Valid && q.id != request.id);
            if (isExist)
            {
                throw new BadRequestException(RequestEnum.ToolStorageNoIsExist);
            }

            if (string.IsNullOrEmpty(request.code) || string.IsNullOrEmpty(request.name) || string.IsNullOrEmpty(request.ipaddress) ||
                string.IsNullOrEmpty(request.print_category))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var entity = _lineStorageRepository.Get(request.id);
            if (entity == null || entity.status != (int) RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.storage_code = request.code.Trim();
            entity.storage_name = request.name;
            entity.ipaddress = request.ipaddress;
            entity.macaddress = request.macaddress;
            entity.com_port = request.com_port.ToInt();
            entity.print_category = request.print_category.ToInt();
            entity.print_port = request.print_port;
            _lineStorageRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult DeleteLineStorage(int id)
        {
            var entity = _lineStorageRepository.Get(id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.status = (int) RowState.Invalid;
            _lineStorageRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetLineStorages(int sectionId)
        {
            var query = _lineStorageRepository.GetList(q =>
                q.section_id == sectionId && q.project_id == ProjectId && q.status == (int) RowState.Valid);

            var response = query.Select(m => new
            {
                code = m.storage_code,
                name = m.storage_name,
                ipaddress = m.ipaddress,
                macaddress = m.macaddress,
                com_port = m.com_port,
                print_category = m.print_category,
                print_port = m.print_port
            });

            return new ObjectResult(response.ToList());
        }
    }
}