package com.red.circle.other.app.command.sys.query;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.convertor.sys.SysConfigAppConvertor;
import com.red.circle.other.app.dto.clientobject.sys.GameListConfigCO;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.infra.database.cache.service.other.GameListCacheService;
import com.red.circle.other.infra.database.rds.service.live.RoomMemberService;
import com.red.circle.other.infra.database.rds.service.sys.GameListConfigService;
import com.red.circle.other.inner.enums.live.RoomUserRolesEnum;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.text.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 游戏配置列表.
 *
 * @author pengliang on 2022/6/10
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GameListConfigQryExe {

  private static final String COMMON = "COMMON";
  private final UserRegionGateway userRegionGateway;
  private final SysConfigAppConvertor sysConfigAppConvertor;
  private final GameListCacheService gameListCacheService;
  private final RoomMemberService roomMemberService;
  private final GameListConfigService gameListConfigService;

  public List<GameListConfigCO> execute(AppExtCommand cmd) {
    List<GameListConfigCO> configs = listGameListConfig(cmd);

    if (CollectionUtils.isEmpty(configs)) {
      return configs;
    }
    // 弹幕游戏
    configs = isBarrageGame(cmd, configs);

    // 获得用户区域
    String regionId = userRegionGateway.getRegionId(cmd.requiredReqUserId());

    return configs.stream()
        .filter(configCO ->
            StringUtils.isBlank(configCO.getRegions()) || configCO.getRegions()
                .contains(regionId)
        ).toList();
  }

  private List<GameListConfigCO> isBarrageGame(AppExtCommand cmd, List<GameListConfigCO> configs) {
    // 是否弹幕游戏
    configs.forEach(
            config -> {
              Map<String, String> stringStringMap = parseUrlParams(config.getGameCode());
              config.setIsBarrageGame(StringUtils.isNotBlank(stringStringMap.get("isBarrageGame")));
              config.setThirdGameId(StringUtils.isNotBlank(stringStringMap.get("thirdGameId")) ?
                      Integer.parseInt(stringStringMap.get("thirdGameId")) : null);
            }
    );
    if (StringUtils.isBlank(cmd.getRoomSessionId())) {
      log.info("房间ID 为空，返回所有弹幕游戏");
      return configs;
    }
    // 判断是否是房主或房间管理员
    RoomUserRolesEnum roomUserRoles = roomMemberService.getRoomUserRoles(cmd.requiredReqUserId(),
            Long.parseLong(cmd.getRoomSessionId()));
    // 如果不是房主或房间管理员，不返回弹幕游戏
    if (!roomUserRoles.checkHomeownerOrAdmin()) {
      configs = configs.stream()
              .filter(config -> !config.getIsBarrageGame()).toList();
    }
    return configs;
  }

  // 解析 游戏 URL 参数
  private Map<String, String> parseUrlParams(String url) {
    Map<String, String> params = new HashMap<>();
    int queryIndex = url.indexOf("?");
    if (queryIndex != -1) {
      String query = url.substring(queryIndex + 1);
      String[] paramPairs = query.split("&");
      for (String paramPair : paramPairs) {
        String[] parts = paramPair.split("=");
        if (parts.length == 2) {
          params.put(parts[0], parts[1]);
        }
      }
    }
    return params;
  }

  private List<GameListConfigCO> listGameListConfig(AppExtCommand cmd) {
    return getGameListConfigs(cmd);
  }

  private List<GameListConfigCO> getGameListConfigs(AppExtCommand cmd) {

    String data = gameListCacheService.listCache(cmd.requireReqSysOrigin(),
        sysOrigin -> JacksonUtils.toJson(sysConfigAppConvertor.toListGameListConfigCO(
            gameListConfigService.listShowcaseConfig(cmd.requireReqSysOrigin(),cmd.reqVersionIsGameNew(),!cmd.reqVersionIs191()))),cmd.reqVersionIsGameNew(),cmd.getReqAppIntel().getVersion());

    if (StringUtils.isBlank(data)) {
      return Lists.newArrayList();
    }

    List<GameListConfigCO> configs = JacksonUtils.readValue(data, new TypeReference<>() {
    });
    if (CollectionUtils.isEmpty(configs)) {
      return Lists.newArrayList();
    }

    if (cmd.checkAndroid()) {
      return configs.stream()
          .filter(config -> Objects.equals(config.getClientOrigin(), "ANDROID") || Objects
              .equals(config.getClientOrigin(), COMMON))
          .toList();
    }

    if (cmd.checkIos()) {
      return configs.stream()
          .filter(config -> Objects.equals(config.getClientOrigin(), "IOS") || Objects
              .equals(config.getClientOrigin(), COMMON))
          .toList();
    }
    return configs.stream()
        .filter(config -> Objects.equals(config.getClientOrigin(), COMMON))
        .toList();
  }

}
