package com.eactive.testmaster.server.controller;

import com.eactive.testmaster.server.dto.ServerDTO;
import com.eactive.testmaster.server.dto.ServerSearch;
import com.eactive.testmaster.server.entity.Server;
import com.eactive.testmaster.server.mapper.ServerMapper;
import com.eactive.testmaster.server.service.ServerMgmtService;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/servers")
public class ServerRestController {

    private final ServerMgmtService serverMgmtService;

    private final ServerMapper serverMapper;

    public ServerRestController(ServerMgmtService serverMgmtService, ServerMapper serverMapper) {
        this.serverMgmtService = serverMgmtService;
        this.serverMapper = serverMapper;
    }

    @GetMapping("/list.do")
    @Secured("ROLE_API_TESTER")
    public ResponseEntity<List<ServerDTO>> listView(@ModelAttribute("serverSearch") ServerSearch serverSearch) {
        Pageable maxPageable = PageRequest.of(0, Integer.MAX_VALUE);

        Page<Server> page = serverMgmtService.findAll(serverSearch.buildSpecification(), maxPageable);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Total-Count", String.valueOf(page.getTotalElements()));
        headers.add("X-Total-Pages", String.valueOf(page.getTotalPages()));
        headers.add("X-Current-Page", String.valueOf(page.getNumber()));
        headers.add("X-Page-Size", String.valueOf(page.getSize()));
        return new ResponseEntity<>(serverMapper.map(page.getContent()), headers, HttpStatus.OK);
    }
}
