package com.sonic.common.client;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.sonic.common.AppRuntime;
import com.sonic.common.enums.AppEnv;
import com.sonic.common.rpc.RpcClient;
import lombok.Data;

public class BsClientFactory {

    private AppRuntime appRuntime;
    private RpcClient rpcClient;
    private boolean isDummy;
    private AppCenterClient appCenterClient;
    private String host;

    private BsClientFactory() {
        // used to prevent creating instance directly
    }

    // public identifier if other client not build in bs-client, can also use resolveClientBuilder
    public <T extends AbstractBsClient.Builder> T resolveClientBuilder(T builder) {
        builder.setAppRuntime(appRuntime);
        builder.setRpcClient(rpcClient);
        builder.setDummy(isDummy);
        builder.setAppCenterClient(appCenterClient);
        builder.setHost(host);
        return builder;
    }

    public static Builder builder() {
        return new Builder();
    }

    @Data
    public static class Builder {
        private AppRuntime appRuntime;
        private RpcClient rpcClient;
        private boolean isDummy;
        private AppCenterClient appCenterClient;
        private String host = "";

        public Builder appRuntime(AppRuntime appRuntime) {
            this.appRuntime = appRuntime;
            return this;
        }

        public Builder rpcClient(RpcClient rpcClient) {
            this.rpcClient = rpcClient;
            return this;
        }

        public Builder appCenterClient(AppCenterClient appCenterClient) {
            this.appCenterClient = appCenterClient;
            return this;
        }

        public Builder host(String host) {
            this.host = Strings.nullToEmpty(host);
            return this;
        }

        public BsClientFactory build() {
            Preconditions.checkArgument(!Strings.isNullOrEmpty(appRuntime.getAppId()), "缺少appId");
            Preconditions.checkArgument(appRuntime.getEnv() != null, "缺少 appEnv");
            Preconditions.checkArgument(rpcClient != null, "缺少 rpcClient");
            Preconditions.checkArgument(appCenterClient != null, "缺少 appCenterClient");

            BsClientFactory factory = new BsClientFactory();
            factory.appRuntime = appRuntime;
            if (appRuntime.getEnv() == AppEnv.unittest) {
                factory.isDummy = true;
                return factory;
            }

            factory.rpcClient = rpcClient;
            factory.appCenterClient = appCenterClient;
            factory.host = host;
            return factory;
        }
    }
}
