import { ethers } from 'ethers';
import { Counter } from '@typechain/Counter';
import * as counterJson from '../out/Counter.sol/Counter.json';

export class Client {
  private provider: ethers.providers.Provider;
  private splendid: Counter;
  private splendidInterface: ethers.utils.Interface;

  constructor(rpcUrl: string, splendidContractAddress: string, signer?: ethers.Signer) {
    if (!rpcUrl) {
      throw new Error('RPC URL passed to client must be defined');
    }

    if (!splendidContractAddress) {
      throw new Error('RPC URL passed to client must be defined');
    }

    this.provider = new ethers.providers.JsonRpcProvider(rpcUrl);
    if (signer) {
      const signerWithProvider = signer.connect(this.provider);
      this.splendid = new ethers.Contract(splendidContractAddress, counterJson.abi, signerWithProvider) as Counter;
    } else {
      this.splendid = new ethers.Contract(splendidContractAddress, counterJson.abi, this.provider) as Counter;
    }

    this.splendidInterface = new ethers.utils.Interface(counterJson.abi);
  }

  public async createCollection(): Promise<ethers.ContractTransaction> {
    return this.splendid.createCollection();
  }

  public async parseEventLog(data: string, topics: string[]): Promise<ethers.utils.LogDescription> {
    return this.splendidInterface.parseLog({
      topics,
      data,
    });
  }
}
