package com.red.circle.other.app.command.party3rd.callback.im;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.tool.core.exception.NotFoundStrategyException;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;

/**
 * 策略工厂.
 *
 * @author pengliang on 2020/7/22
 */
@Component
public class FactoryImCallbackToServerStrategy {

  private final Map<String, ImCallbackStrategy> strategyCurrentMap = new ConcurrentHashMap<>();

  public FactoryImCallbackToServerStrategy(
      Map<String, ImCallbackStrategy> strategyMap) {
    strategyCurrentMap.putAll(strategyMap);
  }

  public ImCallbackStrategy getStrategy(String body) {

    ImCallbackStrategy strategy = strategyCurrentMap.get(getCallbackCommand(body));
    if (strategy == null) {
      throw new NotFoundStrategyException("no strategy defined", body);
    }
    return strategy;
  }

  private String getCallbackCommand(String body) {
    JsonElement jsonElement = JsonParser.parseString(body);
    ResponseAssert.notNull(ResponseErrorCode.REQUEST_PARAMETER_ERROR, jsonElement);
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    ResponseAssert.notNull(ResponseErrorCode.REQUEST_PARAMETER_ERROR, jsonObject);
    String command = jsonObject.get("CallbackCommand").getAsString();
    ResponseAssert.isTrue(ResponseErrorCode.REQUEST_PARAMETER_ERROR,
        StringUtils.isNotBlank(command));
    return command;
  }

}
