package ch.unisg.roster.roster.adapter.in.web;

import ch.unisg.roster.roster.domain.Roster;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import ch.unisg.roster.roster.application.port.in.ApplyForTaskCommand;
import ch.unisg.roster.roster.application.port.in.ApplyForTaskUseCase;
import ch.unisg.roster.roster.domain.ExecutorInfo;
import ch.unisg.roster.roster.domain.Task;
import org.springframework.web.server.ResponseStatusException;

import javax.validation.ConstraintViolationException;

@RestController
public class ApplyForTaskWebController {
    private final ApplyForTaskUseCase applyForTaskUseCase;

    public ApplyForTaskWebController(ApplyForTaskUseCase applyForTaskUseCase) {
        this.applyForTaskUseCase = applyForTaskUseCase;
    }

    // TODO fix return type
    /**
    *   Checks if task is available for the requesting executor.
    *   @return a task or null if no task found
    **/
    @PostMapping(path = "/task/apply", consumes = {"application/json"})
    public ResponseEntity<String> applyForTask (@RequestBody ExecutorInfo executorInfo) {

        ApplyForTaskCommand command = new ApplyForTaskCommand(executorInfo.getExecutorType(),
            executorInfo.getExecutorURI());

        Task task =  applyForTaskUseCase.applyForTask(command);

        if (task == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }

        try {

            String executorType = command.getTaskType().getValue().toString();
            String executorURI = command.getExecutorURI().getValue().toString();

            String jsonPayLoad = new JSONObject()
                .put("executorType", executorType)
                .put("executorURI", executorURI)
                .toString();

            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.add("Content-Type", "application/json");

            return new ResponseEntity<>(jsonPayLoad, responseHeaders, HttpStatus.CREATED);
        } catch (ConstraintViolationException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
        }

    }
}
