package com.platform.plugs.live.handlers;

import com.aliyuncs.AcsRequest;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.platform.plugs.common.rpc.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author TONG
 * @Date 2019/2/18 16:53
 **/
public abstract class LiveHandler {

    private final Log log = LogFactory.getLog(LiveHandler.class);

    private CommonRpc commonRpc;

    public LiveHandler(CommonRpc commonRpc) {
        this.commonRpc = commonRpc;
    }

    public RpcResponse rpc(String action, MethodType methodType, Object requestEntity) {
        RpcResponse response = commonRpc.rpc(action, methodType, requestEntity);
        return response;
    }

    public RpcResponse rpc(AcsRequest request) {
        return rpc(request, null);
    }

    public <T> RpcResponse<T> rpc(AcsRequest request, ResponseWrapper wrapper) {

        if (request == null) {
            return new RpcResponse(RpcResponse.ERROR_STATUS, ResponseResult.ERROR, ErrorCode.NoRequest.toString(), "no request");
        }
        RpcResponse response = null;
        String errorCode = ErrorCode.UnknownError.toString(), errorMsg = "unknownError exception";
        try {
            AcsResponse acsResponse = commonRpc.rpc(request);
            if (acsResponse != null) {
                response = new RpcResponse();
                if (wrapper != null) {
                    response.setResponse(wrapper.responseWrap(acsResponse));
                }
                return response;
            }
        } catch (ClientException e) {
            log.error(request.getSysActionName() + " error, errorCode : " + e.getErrCode() + ", errorMsg : " + e.getErrMsg());
            errorCode = e.getErrCode();
            errorMsg = e.getErrMsg();
        }
        response = new RpcResponse(RpcResponse.ERROR_STATUS, ResponseResult.ERROR, errorCode, errorMsg);

        return response;
    }
}