import {Injectable} from '@angular/core';
import {EthService} from '../eth.service';
import {Contract} from 'web3-eth-contract';

const abi = require('../../assets/contract/HelloWorld.json');

@Injectable({
  providedIn: 'root'
})
export class TestContractService {
  private contract: Contract = null;

  constructor(private ethService: EthService) {
    ethService.validProviderAndAccount$.subscribe(() => this.loadContract());
  }

  private get eth() {
    return this.ethService.eth;
  }

  private async getAccount() {
    return await this.ethService.getDefaultAccount();
  }

  private async loadContract() {
    const address = this.ethService.contractAddresses.HelloWorld;
    console.log('load contract at address', address);
    this.contract = new this.eth.Contract(abi, address, {
      from: await this.getAccount(),
      gas: 1500000,
      gasPrice: '100000000000',
    });
  }

  async increment() {
    const contract = this.contract;
    await contract.methods.add().send()
      .then(value => console.log('increased!', value))
      .catch(e => console.error('error while calling add', e));
  }

  async update(): Promise<number> {
    const contract = this.contract;
    const result = await contract.methods.getCounter().call()
      .catch(e => console.error('error while calling getCounter', e));
    return result as number;
  }
}
