package org.mycoradar;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
public class Controller {

    private Logger logger = LoggerFactory.getLogger(getClass().toString());

    @Autowired // This means to get the bean called ContactRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private ContactRepository contactRepository;

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    private String home() {
        logger.info("home controller called");
        return "Hello World!";
    }

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/addContactWithServerTime", method = RequestMethod.POST)
    @ResponseBody
    public HttpStatus addContactWithServerTime(@RequestParam String device_id){
        Date now = new Date();
        Timestamp timestamp_positive = new Timestamp(now.getTime());
        Contact n = new Contact(device_id, timestamp_positive);
        contactRepository.save(n);
        return HttpStatus.OK;
    }

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    @ResponseBody
    public HttpStatus addContact(@RequestParam String device_id,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime date_positive) {
        Timestamp timestamp_positive = Timestamp.valueOf(date_positive);
        Contact n = new Contact(device_id, timestamp_positive);
        contactRepository.save(n);
        return HttpStatus.OK;
    }

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/getContact", method = RequestMethod.GET)
    @ResponseBody
    public Boolean getContact(@RequestParam List<String> device_ids) {
        Iterable<Contact> contactListe = contactRepository.findAll();
        Iterator<Contact> iterator = contactListe.iterator();
        while (iterator.hasNext()) {
            Contact contact = iterator.next();
            if (device_ids.contains(contact.getDevice_id())){
                  return true;
            }
        }
        return false;
    }
}