package quant.rich;
import lombok.extern.slf4j.Slf4j;
import quant.rich.emoney.EmoneyAutoApplication;
import quant.rich.emoney.util.SmartResourceResolver;

import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import io.micrometer.core.instrument.util.IOUtils;

@SpringBootTest
@ContextConfiguration(classes = EmoneyAutoApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
@Slf4j
public class RelativeEmoneyScraper {
    
    static final Pattern nonParamsIndexDetailPattern = Pattern.compile("\\[(\\{(id:\\d+,?|data:\\[\\{(title:\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*?\",?|items:\\[(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*?\",?)+],?|image:\".*?\",?)+\\}+\\],?|name:\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*?\",?|nameCode:\"\\d+\",?)+\\},?)+\\]", Pattern.DOTALL);
    
    @Test
    void test() throws Exception {

        String js = IOUtils.toString(SmartResourceResolver.loadResource("./conf/extra/indexJs.js"), StandardCharsets.UTF_8);
        
        String jsArrayText;
        Matcher m = nonParamsIndexDetailPattern.matcher(js);
        if (m.find()) jsArrayText = m.group(); else return;
        ScriptEngine jsEngine = new ScriptEngineManager().getEngineFactories().get(0).getScriptEngine();
        Object result = jsEngine.eval("JSON.stringify(" + jsArrayText + ")");
        if (result != null && result instanceof String resultString)
            log.info(resultString);
        
    }
}
