import { LockerService } from '../services/LockerService';
import { IndexProductStatus, FundProductStatus, DerivativeProviders, FundType } from '../interfaces/Enums';

export default class Mutex {

  private product;
  private lockerService: LockerService;

  public constructor(product) {
    this.product = product;
    this.lockerService = new LockerService();
  }

  public async checkLocker(lockerCategory: DerivativeProviders) {

    // Has no locker configured in the product
    if (lockerCategory === null) { return { message: `Derivative is ready`, flag: true }; }
    // Has locker configured in the product
    const lockerAddress = await this.product.service.getComponentAddress(DerivativeProviders.LOCKER);
    const lockerAvailable = await this.lockerService
      .checkLockerByTime(this.product.address, lockerCategory, lockerAddress);

    return { message: `Checking the time lock ${lockerAvailable}`, flag: lockerAvailable };
  }
  public async checkMutex(
    requiredProductStatus: IndexProductStatus | FundProductStatus,
  ): Promise<{
    message: string,
    flag: boolean,
    productStatus: IndexProductStatus | FundProductStatus,
  }> {

    const productStatusType = this.getProductStatusType();

    const productStatus = await this.product.getProductStatus();

    // IS BUSY, we check is busy in this task or different one
    // If is the type we are trying to executing,
    const mutexOK = productStatus === requiredProductStatus || productStatus === productStatusType.AVAILABLE;
    const message = mutexOK ? `Mutex is okay` : `Mutex is not okay, derivative is busy on ${productStatus}`;
    return {
      message,
      flag: mutexOK,
      productStatus,
    };
  }

  public getProductStatusType() {
    if (this.product.fundType === FundType.Index) { return IndexProductStatus; }
    if (this.product.fundType === FundType.Fund) { return FundProductStatus; }
    // if (this.product.fundType === FundType.Future) { return FutureProductStatus; }

    throw new Error('Unknown product status encountered');
  }
}
