using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using detect.gui.Models;
using detect.gui.Models.Entities;

namespace detect.gui.Services.Detect;

public class DetectAuthorityService : ServiceBase<DetectAuthorityService, AuthorityEntity>
{
    public ApiResponse<PagedResult<AuthorityEntity>> Search(int? id, string? name = "", int pageNum = 1, int pageSize = 10)
    {
        Expression<Func<AuthorityEntity,bool>> filter = x =>
            (id == null || x.Id == null || x.Id == id) &&
            (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(x.Name) || x.Name.Contains(name));
        var total = Count(filter);
        var items = FindList(filter, "CreateTime", true)
            .Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
        var pagedResult = new PagedResult<AuthorityEntity>(pageNum, pageSize, total, items);
        return new ApiResponse<PagedResult<AuthorityEntity>>(0, "success", pagedResult);
    }
    
    public ApiResponse<AuthorityEntity?> ListById(long id)
    {
        var item = Find(x => x.Id == id);
        return new ApiResponse<AuthorityEntity?>(0, "success", item);
    }
    
    public ApiResponse<AuthorityEntity?> ListOne(int? id, string? name = "")
    {
        Expression<Func<AuthorityEntity,bool>> filter = x =>
            (id == null || x.Id == null || x.Id == id) &&
            (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(x.Name) || x.Name.Contains(name));
        var item = Find(filter);
        return new ApiResponse<AuthorityEntity?>(0, "success", item);
    }
    
    public ApiResponse<List<AuthorityEntity>?> ListAll()
    {
        var items = FindList(x => true, "Id", true)
            .ToList();
        return new ApiResponse<List<AuthorityEntity>?>(0, "success", items);
    }
    
    public ApiResponse<AuthorityEntity?> AddData(AuthorityEntity entity)
    {
        var data = Add(entity);
        return new ApiResponse<AuthorityEntity?>(0, "success", data);
    }
    
    public ApiResponse<AuthorityEntity?> UpdateData(AuthorityEntity entity)
    {
        return new ApiResponse<AuthorityEntity?>(Update(entity) ? 0 : -1, "success", null);
    }
    
    public ApiResponse<AuthorityEntity?> DeleteById(long id)
    {
        Delete(x => x.Id == id);
        return new ApiResponse<AuthorityEntity?>(0, "success", null);
    }
    
    public ApiResponse<AuthorityEntity?> DeleteData(AuthorityEntity entity)
    {
        Delete(entity);
        return new ApiResponse<AuthorityEntity?>(0, "success", null);
    }
}