package com.yihu.hos.arbiter.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.models.BrokerServer;
import com.yihu.hos.arbiter.models.Endpoint;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @created Airhead 2016/7/27.
 */
@Service("endpointService")
public class EndpointService {
    private static final Logger logger = LogManager.getLogger(BrokerServerService.class);
    @Autowired
    private BrokerServerService brokerServerService;
    @Autowired
    private MongoOperations mongoOperations;

    public void save(Endpoint endpoint) {
        mongoOperations.save(endpoint);
    }

    public Endpoint get(String serviceName) {
        return mongoOperations.findOne(new Query(), Endpoint.class);
    }

    public void update(Endpoint endpoint) {

    }

    public void trigger(String msg) {
        System.out.println(msg);
        BrokerServer brokerServer = brokerServerService.get();
        if (brokerServer == null) {
            logger.trace("can not find a valid broker server.");
            return;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Endpoint endpoint = objectMapper.readValue(msg, Endpoint.class);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            switch (endpoint.getEvent()) {
                case "endpointRegister": {
                    this.save(endpoint);
                    break;
                }

                case "endpointOnService": {
                    this.save(endpoint);
                    break;
                }

                case "endpointOffService": {
                    this.update(endpoint);
                    break;
                }

                default:
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
