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.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class DashboardPageRepository : ApiConfigRepositoryBase<siger_project_dashboard_page>,
        IDashboardPageRepository
    {
        private readonly ApiConfigDbContext _context;

        public DashboardPageRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public ResponseGetDashboardPage GetDashPaged(int id)
        {
            var query = from q in _context.siger_project_dashboard_page
                join p in _context.siger_project_dashboard_page_patial on q.page_code equals p.page_code
                join c in _context.siger_project_dashboard_page_patial_condition on p.page_patial_code equals c
                    .page_patial_code
                where q.status == (int)RowState.Valid && q.id == id
                select new ResponseGetDashboardPage
                {
                    id = q.id,
                    page_title = q.page_title,
                    page_code = q.page_code,
                    description = q.page_description,
                    x = p.x,
                    y = p.y,
                    w = p.w,
                    h = p.h,
                    page_patial_code = p.page_patial_code,
                    type = c.type,
                    page_patial_condition_code = c.page_patial_condition_code
                };
            return query.FirstOrDefault();
        }

        public IPagedCollectionResult<ResponseGetDashboardPage> GetPagedDashPagedCollection(string name, int page, int pagesize)
        {
            var query = from q in _context.siger_project_dashboard_page
                where q.status == (int) RowState.Valid
                select new ResponseGetDashboardPage
                {
                    id = q.id,
                    page_title = q.page_title,
                    page_code = q.page_code,
                    description = q.page_description,
                };
            Expression<Func<ResponseGetDashboardPage, bool>> nameExpression = q => true;
            if (!string.IsNullOrWhiteSpace(name))
            {
                nameExpression = q => q.description.Contains(name);
            }

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

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