package com.yihu.hos.arbiter.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.models.BrokerServer;
import com.yihu.hos.arbiter.services.BrokerServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * @created Airhead 2016/7/27.
 */
@RestController
@RequestMapping("/brokerServer")
public class BrokerServerController {
    @Autowired
    private BrokerServerService brokerServerService;

    @RequestMapping(method = RequestMethod.POST)
    public void save(String brokerServer) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            BrokerServer server = objectMapper.readValue(brokerServer, BrokerServer.class);
            server.setUpdateTime(new Date());
            brokerServerService.save(server);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public String get() {
        try {
            BrokerServer brokerServer = brokerServerService.get();
            if (brokerServer == null) {
                return "{}";
            }

            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(brokerServer);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return "{}";
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public String delete(String brokerServer) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            BrokerServer server = objectMapper.readValue(brokerServer, BrokerServer.class);
            server.setUpdateTime(new Date());
            brokerServerService.delete(server);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "{}";
    }
}
