import {Component} from '@angular/core';
import {EthService} from '../eth.service';
import {tap} from 'rxjs/operators';
import {RandomGameService} from '../random-game/random-game.service';

@Component({
  selector: 'app-settings',
  templateUrl: './settings.component.html',
  styleUrls: ['./settings.component.scss']
})
export class SettingsComponent {

  defaultAccount$ = this.ethService.defaultAccount$.pipe(
    tap(a => console.log('account', a))
  );

  constructor(private ethService: EthService,
              private contractService: RandomGameService) {
  }

  get useMetaMask() {
    return this.ethService.getProvider() === 'metamask';
  }

  set useMetaMask(val: boolean) {
    if (val && !this.useMetaMask) {
      this.ethService.setProvider('metamask');
    } else if (!val && this.useMetaMask) {
      this.ethService.setProvider('local');
    }
  }

  async switchToNewAccountAndSendEther() {
    const account = this.ethService.eth.accounts.create();
    this.ethService.eth.sendTransaction({
      from: await this.ethService.getDefaultAccount(),
      to: account.address,
      value: this.ethService.utils.toWei('10', 'ether'),
      gas: 30000,
      gasPrice: await this.ethService.gasPrice(),
    }).on('transactionHash', async value => {
      console.log('transaction done', value);
      this.ethService.setNewDefaultAccount(account);
      await this.ethService.unlockAccount();
    });
  }

  async switchToDefaultAccount() {
    this.ethService.switchToDefaultAccount();
  }

  pendingTransactions() {
    this.ethService.pendingTransactions();
  }

  deploy() {
    this.contractService.deploy();
  }
}
