package com.yihu.hos.arbiter.services;

import com.yihu.hos.arbiter.models.BrokerServer;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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;

/**
 * @created Airhead 2016/7/27.
 */
@Service
public class BrokerServerService {
    private static final Logger logger = LogManager.getLogger(BrokerServerService.class);

    @Autowired
    private MongoOperations mongoOperations;

    public void save(BrokerServer brokerServer) {
        Query query = new Query();
        query.addCriteria(Criteria.where("hostName").is(brokerServer.getHostName()));
        query.addCriteria(Criteria.where("hostAddress").is(brokerServer.getHostAddress()));

        Update update = new Update();
        update.set("hostName", brokerServer.getHostName());
        update.set("hostAddress", brokerServer.getHostAddress());
        update.set("port", brokerServer.getPort());
        update.set("updateTime", brokerServer.getUpdateTime());
        update.set("enable", brokerServer.isEnable());

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

    /**
     * 暂不提供动态均衡算法，只是随机返回一个。
     *
     * @return
     */
    public BrokerServer get() {
        Query query = new Query();
        query.addCriteria(Criteria.where("enable").is(true));
        query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "updateTime")));
        return mongoOperations.findOne(query, BrokerServer.class);
    }

    public void delete(BrokerServer brokerServer) {
        mongoOperations.remove(brokerServer);
    }
}
