package com.sjyt.icom.asst.context.handle.srs;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sjyt.icom.asst.common.model.message.VerifyClaims;
import com.sjyt.icom.asst.common.event.SrsCallBackEvent;
import com.sjyt.icom.asst.common.util.FuncUtils;
import com.sjyt.icom.asst.common.util.JjwtUtil;
import com.sjyt.icom.asst.common.util.UrlUtils;
import com.sjyt.icom.asst.conf.properties.RtspAppProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * <p>参数验证</p>
 * 位于链首
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/14 13:52
 */
@Slf4j
@Component
@AllArgsConstructor
public class RtspParamHandle extends RtspHandle {
    private final RtspAppProperties config;

    /**
     * 执行链
     *
     * @param event 事件对象
     * @return r
     */
    @Override
    public Integer doChain(SrsCallBackEvent event) {
        log.info("UrlFormatHandle执行");
        //Event非空 》 param非空 》 token校验 》claims非空 》 one2OneUrl
        return Optional.ofNullable(event)
                .flatMap(e -> Optional.ofNullable(e.getParam())
                        .map(param -> {
                            Map<String, String> urlParams = UrlUtils.getUrlParams(param);
                            String token = urlParams.get(config.getTokenName());
                            return JjwtUtil.getClaims(token);
                        })
                        .filter(it -> !FuncUtils.checkObjFieldIsNullAndBlank(it, null)))
                .map(it -> {
                    event.setClaims(it);
                    return one2OneUrl(event);
                }).orElseGet(() -> {
                    log.error("RtspParamHandle校验失败");
                    return FAIL;
                });
    }

    private int meetUrl(SrsCallBackEvent event) {
        //todo 处理
        return handle.doChain(event);
    }

    private int one2OneUrl(SrsCallBackEvent event) {
        final String app = event.getApp();
        final String appName = Optional.ofNullable(app)
                .filter(it -> it.startsWith(config.getApp()))
                .map(it -> it.substring(0, config.getApp().length()))
                .orElse(null);
        event.setAppName(appName);
        return handle.doChain(event);
    }
}
