export default class PerformanceElementCheck {
  /**
   * @param {string} elementDescription
   * @param {WebdriverIO.Element} element
   * @param {boolean} alsoCheckVisibility
   * @param {number} timeout
   */
  constructor(elementDescription, element, alsoCheckVisibility, timeout = 30000, addToPassedTime = 0) {
    this.elementDescription = elementDescription;
    this.element = element;
    this.alsoCheckVisibility = alsoCheckVisibility;
    this.timeout = timeout;
    this.navStart = 0;
    this.timestamp = 0;
    this.error = false;
    this.addToPassedTime = addToPassedTime;
  }

  async fullfill() {
    let start = new Date().getTime();
    try {
      await expect(this.element).toExist({
        wait: this.timeout,
        message: 'Element ' + this.elementDescription + ' did not become present',
        interval: 100
      })
      if (this.alsoCheckVisibility) {
        let passedTime = (new Date().getTime()) - start;
        let newTimeout = (this.timeout - passedTime);
        if (newTimeout < 100) {
          newTimeout = 100;
        }
        try {
          await this.element.scrollIntoView();
        } catch (error) {
          try {
            await expect(this.element).toExist({
              wait: newTimeout,
              message: 'Element ' + this.elementDescription + ' did not become present',
              interval: 100
            });
            await (this.element).scrollIntoView();
            passedTime = (new Date().getTime()) - start;
            newTimeout = (this.timeout - passedTime);
            if (newTimeout < 100) {
              newTimeout = 100;
            }
          } catch (error1) {
            await browser.pause(1000);
            try {
              await (this.element).scrollIntoView();
            } catch (error2) {
              throw error1;
            }
            passedTime = (new Date().getTime()) - start;
            newTimeout = (this.timeout - passedTime);
            if (newTimeout < 100) {
              newTimeout = 100;
            }
          }
        }

        await expect(this.element).toBeDisplayed({
          wait: newTimeout,
          message: 'Element ' + this.elementDescription + ' did not become visible',
          interval: 100
        });
      }
    } catch (error) {
      error.message += ' within ' + ((new Date().getTime() - start) + this.addToPassedTime) + ' ms'
      this.error = {
        source: 'PerformanceElementCheck',
        message: error.message,
        element: this.element.selector,
        stack: error.stack
      };
    }
    this.timestamp = new Date().getTime();
  }
}


