package com.yihu.hos.arbiter.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.arbiter.models.ArbiterServer;
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.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * @author Airhead
 * @since 2016/12/9.
 */
@Service
public class ArbiterServerService {
    private static final Logger logger = LogManager.getLogger(ArbiterServerService.class);

    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private ArbiterServerConfiguration configuration;
    @Autowired
    private ObjectMapper objectMapper;

    public ArbiterServerService() {
    }

    public void start() {
        //中心Arbiter服务器直接注册
        if (configuration.isCentral()) {
            return;
        }

        ArbiterServer arbiterServer = new ArbiterServer();
        arbiterServer.setTenant(configuration.getTenant());
        arbiterServer.setUrl(configuration.getTerminalUrl());

        this.save(arbiterServer);
    }

    public void save(ArbiterServer arbiterServer) {
        Query query = new Query();
        query.addCriteria(Criteria.where("tenant").is(arbiterServer.getTenant()));
        Update update = new Update();
        update.set("tenant", arbiterServer.getTenant());
        update.set("url", arbiterServer.getUrl());

        mongoOperations.upsert(query, update, ArbiterServer.class);
    }

    public ArbiterServer get(String tenant) {
        Query query = new Query();
        query.addCriteria(Criteria.where("tenant").is(tenant));

        return mongoOperations.findOne(query, ArbiterServer.class);
    }
}
