package com.printhub.printhub.service.configuration;

import com.printhub.printhub.model.configuration.Printer;
import com.printhub.printhub.repository.configuration.PrinterRepository;
import com.printhub.printhub.specification.configuration.PrinterSpecification;
import com.printhub.printhub.utils.datatables.DataTableBuilder;
import com.printhub.printhub.utils.datatables.DataTableRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class PrinterService {

    @Autowired
    private PrinterRepository printerRepository;

    public Map<String, Object> listDataTable(DataTableRequest dt) {
        // Crear pageable con orden, si existe
        Pageable pageable = dt.hasOrder()
                ? PageRequest.of(dt.getPage(), dt.getSize(),
                        Sort.by(Sort.Direction.fromString(dt.getOrderDirection()), dt.getOrderColumn()))
                : PageRequest.of(dt.getPage(), dt.getSize());

        Specification<Printer> spec = PrinterSpecification.buildSpec(dt);
        Page<Printer> page = printerRepository.findAll(spec, pageable);
        return new DataTableBuilder<>(page, dt.getDraw()).build();

    }
}