import { getLatestABI } from './AbiService';
import Promisify from '../utils/Promisify';
import Config from '../config';
import Services from '../Services';
import { WhitelistType } from '../interfaces/Enums';

export class WhitelistService extends Services {
  private address: string;
  private _contract;

  constructor(address: string) {
    super();
    this.address = address;
  }

  public async contract(): Promise<any> {
    this._contract = await this.rpcService.contract(await getLatestABI('WHITELIST_ABI'), this.address);
    return this._contract;
  }

  public async hasPermission(whitelistAddress: string) {
    if (whitelistAddress === '0x') {
      return false;
    }
    if (!this._contract) {
      this._contract = await this.rpcService.contract(await getLatestABI('WHITELIST_ABI'), this.address);
    }
    const enabled = await Promisify(async (cb) => {
      (await this._contract(whitelistAddress)).enabled(this.address, WhitelistType.Maintenance, cb);
    });
    if (!enabled) {
      return false;
    }
    const isInWhitelist = await Promisify(async (cb) => {
      (await this._contract(whitelistAddress))
        .whitelist(this.address, WhitelistType.Maintenance, Config.walletAddress, cb);
    });
    return isInWhitelist;
  }
}
