package com.yihu.hos.arbiter.configuration;

import com.yihu.hos.core.datatype.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zbus.broker.ZbusBroker;

import java.io.IOException;

/**
 * @author Airhead
 * @since 2016/12/9.
 */
@Configuration
public class ArbiterServerConfiguration {
    @Value("${arbiter.central.url}")
    private String centralUrl;
    @Value("${arbiter.central.port}")
    private Integer centralPort;
    @Value("${arbiter.central.store}")
    private String centralStore;
    @Value("${arbiter.terminal.url}")
    private String terminalUrl;
    @Value("${arbiter.tenant.name}")
    private String tenant;

    private ZbusBroker zbusBroker;

    public String getCentralUrl() {
        return centralUrl;
    }

    public String getTerminalUrl() {
        return terminalUrl;
    }

    public String getTenant() {
        return tenant;
    }

    public boolean isCentral() {
        return StringUtil.isEmpty(centralUrl);
    }

    public Integer getCentralPort() {
        return centralPort;
    }

    public String getCentralStore() {
        return centralStore;
    }

    @Bean
    public ZbusBroker getZbusBroker() {
        try {
            zbusBroker = new ZbusBroker(this.centralUrl);
            return zbusBroker;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void finalize() throws Throwable {
        if (zbusBroker != null) {
            zbusBroker.close();
        }

        super.finalize();
    }

//    public boolean isTerminal() {
//        return !isCentral();
//    }
}
