package ev;

import common.Constant;
import config.Config;
import org.apache.commons.lang3.StringUtils;
import util.Tools;
import java.util.concurrent.TimeUnit;

//todo 仅供参考，实际开发的需要自行封装各个接口
public class Test {
    public static void main(String[] args) throws Exception {
        // step1存证：可以存下response
        String url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201906%2F07%2F20190607002524_vuwod.thumb.400_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1716368525&t=9fc04c1a6db45fc7d675cf25706d1da9";
        String hash = Tools.getHash(url);
        EvSave evSave = new EvSave(Config.platformPubKey, hash, "额外信息");
        EvSaveResp saveResp = evSave.save(Config.platformPrivateKey);
        System.out.println(saveResp);

        // step2查询存证结果：可以等3s再查询存证结果，区块链需要同步账本后才会写入状态到数据库，这个过程会比传统的流程慢一些
        EvQuery evQuery = new EvQuery("", hash, "");
        EvQueryResp queryResp = new EvQueryResp();
        long startTime = System.currentTimeMillis();
        while (Tools.checkTimeout(startTime, Constant.DEFAULT_TIMEOUT) && StringUtils.isEmpty(queryResp.getTxTime())) {
            queryResp = evQuery.query();
            TimeUnit.SECONDS.sleep(1);
        }

        // step3生成存证证书：存证证书可以在需要时再生成；生成前需确认存证已经成功了
        String evId = queryResp.getEvId();
        CreateEvCert createEvCert = new CreateEvCert(evId);
        CreateEvCertResp createEvCertResp = createEvCert.createEvCert();
        System.out.println(createEvCertResp);

        // step4查询存证证书：可以等3s再查询证书生成结果，证书生成是异步的，需要一定时间
        QueryEvCert queryEvCert = new QueryEvCert(evId);
        QueryEvCertResp queryEvCertResp = new QueryEvCertResp();
        while (Tools.checkTimeout(startTime, Constant.DEFAULT_TIMEOUT) && queryEvCertResp.getStatus() != 2) {
            queryEvCertResp = queryEvCert.query();
            TimeUnit.SECONDS.sleep(1);
        }

        System.out.println(queryEvCertResp);
    }
}
