package com.eshore.gringotts.chain.service;

import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.chain.service.sdk.KVDatasource;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple2;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * AssetService
 *
 * @author lanyuanxiaoyao
 * @date 2024-09-27
 */
@Service
public class KVDatasourceService {
    private static final Logger logger = LoggerFactory.getLogger(KVDatasourceService.class);
    private final Client client;
    private final CryptoKeyPair cryptoKeyPair;

    public KVDatasourceService(BcosSDK bcosSDK) {
        client = bcosSDK.getClient(1);
        cryptoKeyPair = client.getCryptoSuite().createKeyPair();
        client.getCryptoSuite().setCryptoKeyPair(cryptoKeyPair);
        logger.debug("create client for group1, account address is {}", cryptoKeyPair.getAddress());
    }

    public String createDatasource() throws ContractException {
        KVDatasource datasource = KVDatasource.deploy(client, cryptoKeyPair);
        return datasource.getContractAddress();
    }

    public void set(String address, String key, String value) {
        if (StrUtil.isBlankIfStr(address)) {
            throw new IllegalArgumentException("address is blank");
        }
        KVDatasource datasource = KVDatasource.load(address, client, cryptoKeyPair);
        datasource.set(key, value);
    }

    public String get(String address, String key) throws ContractException {
        if (StrUtil.isBlankIfStr(address)) {
            throw new IllegalArgumentException("address is blank");
        }
        KVDatasource datasource = KVDatasource.load(address, client, cryptoKeyPair);
        Tuple2<Boolean, String> result = datasource.get(key);
        if (result.getValue1()) {
            return result.getValue2();
        } else {
            throw new ContractException("key not found");
        }
    }
}
