package io.dapr.it.methodinvoke.http;

import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * SpringBoot Controller to handle input binding.
 */
@RestController
public class MethodInvokeController {

    private static final Map<Integer,String> messagesReceived = new HashMap<>();
    private static final List<Person> persons= new ArrayList<>();

    @PostMapping("/messages")
    public void postMessages(@RequestBody String message){
        System.out.println("Controller got message: " + message);
        final Optional<Integer> maxKey = messagesReceived.keySet().stream().max(Integer::compareTo);
        final Integer key = maxKey.orElse(-1)+1;
        messagesReceived.put(key,message);
        System.out.println("Controller save the message: " + message);
    }

    @PutMapping(path = "/messages/{messageId}")
    public void putMessages(@PathVariable Integer messageId, @RequestBody String message){
        messagesReceived.put(messageId,message);
    }

    @DeleteMapping(path = "/messages/{messageId}")
    public void deleteMessages(@PathVariable Integer messageId){
        messagesReceived.remove(messageId);
    }

    @GetMapping(path = "/messages")
    public Map<Integer, String> getMessages() {
        return messagesReceived;
    }

    @PostMapping("/persons")
    public void postPerson(@RequestBody Person person){
        System.out.println("Controller get person: " + person);
        final Optional<Integer> max = persons.stream().map(person1 -> person1.getId()).max(Integer::compareTo);
        final Integer key = max.orElse(-1)+1;
        person.setId(key);
        persons.add(person);
        System.out.println("Controller save the person: " + person);
    }

    @PutMapping(path = "/persons/{personId}")
    public void putPerson(@PathVariable Integer personId, @RequestBody Person person){
        final Optional<Person> auxPerson = persons.stream().filter(person1 -> person1.getId() == personId).findFirst();
        if(auxPerson.isPresent()){
            auxPerson.get().setName(person.getName());
            auxPerson.get().setLastName(person.getLastName());
            auxPerson.get().setBirthDate(person.getBirthDate());
        }
    }

    @DeleteMapping(path = "/persons/{personId}")
    public void deletePerson(@PathVariable Integer personId){
        final Optional<Person> auxPerson = persons.stream().filter(person1 -> person1.getId() == personId).findFirst();
        if(auxPerson.isPresent()) {
            persons.remove(auxPerson.get());
        }
    }

    @GetMapping(path = "/persons")
    public List<Person> getPersons() {
        return persons;
    }
}
