package cn.axzo.msg.center.message.service.impl.v3;

import cn.axzo.msg.center.service.domain.UrlConfig;
import cn.axzo.msg.center.service.domain.UrlConfigVisitor;
import cn.axzo.msg.center.service.domain.UrlConfigWalker;
import cn.axzo.msg.center.service.domain.url.AppUrl;
import cn.axzo.msg.center.service.domain.url.WebUrl;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import static cn.axzo.msg.center.common.utils.PlaceholderResolver.getDefaultResolver;

/**
 * @author yanglin
 */
@Slf4j
@RequiredArgsConstructor
public class UrlParser implements UrlConfigVisitor {

    protected final JSONObject routerParam;

    public void parseUrlConfig(UrlConfig urlConfig) {
        UrlConfigWalker.walkDown(urlConfig, this);
    }

    @Override
    public void visitPcOms(WebUrl pcOms) {
        pcOms.setUrl(parseUrl(pcOms.getUrl()));
    }

    @Override
    public void visitPcCms(WebUrl pcCms) {
        pcCms.setUrl(parseUrl(pcCms.getUrl()));
    }

    @Override
    public void visitPcGaGeneral(WebUrl pcGaGeneral) {
        pcGaGeneral.setUrl(parseUrl(pcGaGeneral.getUrl()));
    }

    @Override
    public void visitAppWorkerIos(AppUrl ios) {
        ios.setUrl(parseUrl(ios.getUrl()));
    }

    @Override
    public void visitAppWorkerAndroid(AppUrl android) {
        android.setUrl(parseUrl(android.getUrl()));
    }

    @Override
    public void visitAppManagerIos(AppUrl ios) {
        ios.setUrl(parseUrl(ios.getUrl()));
    }

    @Override
    public void visitAppManagerAndroid(AppUrl android) {
        android.setUrl(parseUrl(android.getUrl()));
    }

    protected String parseUrl(String url) {
        if (StringUtils.isBlank(url)) return url;
        return getDefaultResolver().resolveByMap(url, routerParam);
    }

}