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