/* global document */
'use strict';

module.exports = {
  async addCookies(cookies, page) {
    for (let j = 0; j < cookies.length; j++) {
      await page.setCookie(cookies[j]);
    }
  },
  async getCode(page, selector) {
    const base64Img = await this.getBase64Image(page, selector);
    return this.ctx.service.ocr.getCode(base64Img);
  },
  async writeLoginCode(page) {
    const code = await this.getCode(page, '#login_checkcode_ico');
    if (!code || code.length !== 4) {
      await page.click('#login_checkcode_ico');
      await page.waitFor(3000);
      return this.writeLoginCode(page, this.ctx);
    }
    this.ctx.logger.info(`aliyun mail: 获取到的验证码是${code}`);
    await page.$eval('#username', input => { input.value = ''; });
    await page.type('#username', this.ctx.app.config.aliyun[0].account);
    await page.type('#login_checkcode', code);
    await page.type('#password', this.ctx.app.config.aliyun[0].password);
    await page.waitFor(3000);
    await page.click('#login_submit_btn');
  },
  async writeTecentLoginCode(page) {
    const code = await this.getCode(page, '#vfcode');
    if (!code) {
      await page.click('#vfcode');
      await page.waitFor(3000);
      return this.writeTecentLoginCode(page);
    }
    this.ctx.logger.info(`tecent mail: 获取到的验证码是${code}`);
    await page.type('#vc', code);
    await page.click('#auto_login_in_five_days_pwd');
    await page.click('#btlogin');
  },
  async getBase64Image(page, selector) {
    return page.evaluate(selector => {
      const img = document.querySelector(selector);
      const element = document.createElement('canvas');
      element.width = img.width;
      element.height = img.height;
      const ctx = element.getContext('2d');
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const dataURL = element.toDataURL('image/png');
      return dataURL.replace('data:image/png;base64,', '');
    }, selector);
  },

  async wait(seconds) {
    return new Promise(resolve => { setTimeout(resolve, seconds); });
  },
};

