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