using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;

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

        public IPagedCollectionResult<ResponseGetLineStorage> GetPagedList(int sectionId, string name, int projectId, int page, int pagesize)
        {
            var query = from q in _context.siger_project_line_storage
                join l in _context.siger_project_level_section on q.section_id equals l.id
                join pl in _context.siger_project_level_section on l.parentid equals pl.id
                where q.project_id == projectId && q.status == (int) RowState.Valid
                select new ResponseGetLineStorage
                {
                    id = q.id,
                    sectionId = q.section_id,
                    sectionName = l.title,
                    parentSectionName =pl.title,
                    storage_code = q.storage_code,
                    storage_name = q.storage_name,
                    ipaddress = q.ipaddress,
                    macaddress = q.macaddress,
                    com_port = q.com_port,
                    print_port = q.print_port ?? "",
                    print_category = q.print_category
                };
            Expression<Func<ResponseGetLineStorage, bool>> sectionIdExpression = q => true;
            if (sectionId != 0)
            {
                sectionIdExpression = q => q.sectionId == sectionId;
            }
            Expression<Func<ResponseGetLineStorage, bool>> nameExpression = q => true;
            if (!string.IsNullOrWhiteSpace(name))
            {
                nameExpression = q => q.storage_name.Contains(name);
            }

            var predicate = sectionIdExpression.And(nameExpression);

            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

            return new PagedCollectionResult<ResponseGetLineStorage>(entities, totalCount);
        }
    }
}
