/**
 * Copyright 2018 Google Inc. All rights reserved.
 * Modifications copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const utils = require('./utils');
const {FFOX, CHROMIUM, WEBKIT, WIN} = utils.testOptions(browserType);
describe('Page.click', function() {
  it('should click the button', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.click('button');
    expect(await page.evaluate(() => result)).toBe('Clicked');
  });
  it('should click svg', async({page, server}) => {
    await page.setContent(`
      
         
    `);
    await page.click('circle');
    expect(await page.evaluate(() => window.__CLICKED)).toBe(42);
  });
  it('should click the button if window.Node is removed', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.evaluate(() => delete window.Node);
    await page.click('button');
    expect(await page.evaluate(() => result)).toBe('Clicked');
  });
  // @see https://github.com/GoogleChrome/puppeteer/issues/4281
  it('should click on a span with an inline element inside', async({page, server}) => {
    await page.setContent(`
      
      woof doggo empty.html `);
    // This await should not hang.
    await page.click('a');
  });
  it('should click the button inside an iframe', async({page, server}) => {
    await page.goto(server.EMPTY_PAGE);
    await page.setContent('
spacer
');
    await utils.attachFrame(page, 'button-test', server.PREFIX + '/input/button.html');
    const frame = page.frames()[1];
    const button = await frame.$('button');
    await button.click();
    expect(await frame.evaluate(() => window.result)).toBe('Clicked');
  });
  // @see https://github.com/GoogleChrome/puppeteer/issues/4110
  // @see https://bugs.chromium.org/p/chromium/issues/detail?id=986390
  // @see https://chromium-review.googlesource.com/c/chromium/src/+/1742784
  it.fail(CHROMIUM || WEBKIT)('should click the button with fixed position inside an iframe', async({page, server}) => {
    await page.goto(server.EMPTY_PAGE);
    await page.setViewportSize({width: 500, height: 500});
    await page.setContent('spacer
');
    await utils.attachFrame(page, 'button-test', server.CROSS_PROCESS_PREFIX + '/input/button.html');
    const frame = page.frames()[1];
    await frame.$eval('button', button => button.style.setProperty('position', 'fixed'));
    await frame.click('button');
    expect(await frame.evaluate(() => window.result)).toBe('Clicked');
  });
  it('should click the button with deviceScaleFactor set', async({browser, server}) => {
    const context = await browser.newContext({ viewport: { width: 400, height: 400 }, deviceScaleFactor: 5 });
    const page = await context.newPage();
    expect(await page.evaluate(() => window.devicePixelRatio)).toBe(5);
    await page.setContent('spacer
');
    await utils.attachFrame(page, 'button-test', server.PREFIX + '/input/button.html');
    const frame = page.frames()[1];
    const button = await frame.$('button');
    await button.click();
    expect(await frame.evaluate(() => window.result)).toBe('Clicked');
    await context.close();
  });
  it('should click the button with px border with offset', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => button.style.borderWidth = '8px');
    await page.click('button', { position: { x: 20, y: 10 } });
    expect(await page.evaluate(() => result)).toBe('Clicked');
    // Safari reports border-relative offsetX/offsetY.
    expect(await page.evaluate(() => offsetX)).toBe(WEBKIT ? 20 + 8 : 20);
    expect(await page.evaluate(() => offsetY)).toBe(WEBKIT ? 10 + 8 : 10);
  });
  it('should click the button with em border with offset', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => button.style.borderWidth = '2em');
    await page.$eval('button', button => button.style.fontSize = '12px');
    await page.click('button', { position: { x: 20, y: 10 } });
    expect(await page.evaluate(() => result)).toBe('Clicked');
    // Safari reports border-relative offsetX/offsetY.
    expect(await page.evaluate(() => offsetX)).toBe(WEBKIT ? 12 * 2 + 20 : 20);
    expect(await page.evaluate(() => offsetY)).toBe(WEBKIT ? 12 * 2 + 10 : 10);
  });
  it('should click a very large button with offset', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => button.style.borderWidth = '8px');
    await page.$eval('button', button => button.style.height = button.style.width = '2000px');
    await page.click('button', { position: { x: 1900, y: 1910 } });
    expect(await page.evaluate(() => window.result)).toBe('Clicked');
    // Safari reports border-relative offsetX/offsetY.
    expect(await page.evaluate(() => offsetX)).toBe(WEBKIT ? 1900 + 8 : 1900);
    expect(await page.evaluate(() => offsetY)).toBe(WEBKIT ? 1910 + 8 : 1910);
  });
  it('should click a button in scrolling container with offset', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => {
      const container = document.createElement('div');
      container.style.overflow = 'auto';
      container.style.width = '200px';
      container.style.height = '200px';
      button.parentElement.insertBefore(container, button);
      container.appendChild(button);
      button.style.height = '2000px';
      button.style.width = '2000px';
      button.style.borderWidth = '8px';
    });
    await page.click('button', { position: { x: 1900, y: 1910 } });
    expect(await page.evaluate(() => window.result)).toBe('Clicked');
    // Safari reports border-relative offsetX/offsetY.
    expect(await page.evaluate(() => offsetX)).toBe(WEBKIT ? 1900 + 8 : 1900);
    expect(await page.evaluate(() => offsetY)).toBe(WEBKIT ? 1910 + 8 : 1910);
  });
  it.skip(FFOX)('should click the button with offset with page scale', async({browser, server}) => {
    const context = await browser.newContext({ viewport: { width: 400, height: 400 }, isMobile: true });
    const page = await context.newPage();
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => {
      button.style.borderWidth = '8px';
      document.body.style.margin = '0';
    });
    await page.click('button', { position: { x: 20, y: 10 } });
    expect(await page.evaluate(() => result)).toBe('Clicked');
    let expected = { x: 28, y: 18 };  // 20;10 + 8px of border in each direction
    if (WEBKIT) {
      // WebKit rounds up during css -> dip -> css conversion.
      expected = { x: 29, y: 19 };
    } else if (CHROMIUM) {
      // Chromium rounds down during css -> dip -> css conversion.
      expected = { x: 27, y: 18 };
    }
    expect(await page.evaluate(() => pageX)).toBe(expected.x);
    expect(await page.evaluate(() => pageY)).toBe(expected.y);
    await context.close();
  });
  it.fail(WEBKIT && WIN)('should wait for stable position', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => {
      button.style.transition = 'margin 500ms linear 0s';
      button.style.marginLeft = '200px';
      button.style.borderWidth = '0';
      button.style.width = '200px';
      button.style.height = '20px';
      // Set display to "block" - otherwise Firefox layouts with non-even
      // values on Linux.
      button.style.display = 'block';
      document.body.style.margin = '0';
    });
    await page.click('button');
    expect(await page.evaluate(() => window.result)).toBe('Clicked');
    expect(await page.evaluate(() => pageX)).toBe(300);
    expect(await page.evaluate(() => pageY)).toBe(10);
  });
  it.fail(WEBKIT && WIN)('should timeout waiting for stable position', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    const button = await page.$('button');
    await button.evaluate(button => {
      button.style.transition = 'margin 5s linear 0s';
      button.style.marginLeft = '200px';
    });
    const error = await button.click({ timeout: 100 }).catch(e => e);
    expect(error.message).toContain('timeout exceeded');
  });
  it('should wait for becoming hit target', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    await page.$eval('button', button => {
      button.style.borderWidth = '0';
      button.style.width = '200px';
      button.style.height = '20px';
      document.body.style.margin = '0';
      document.body.style.position = 'relative';
      const flyOver = document.createElement('div');
      flyOver.className = 'flyover';
      flyOver.style.position = 'absolute';
      flyOver.style.width = '400px';
      flyOver.style.height = '20px';
      flyOver.style.left = '-200px';
      flyOver.style.top = '0';
      flyOver.style.background = 'red';
      document.body.appendChild(flyOver);
    });
    let clicked = false;
    const clickPromise = page.click('button').then(() => clicked = true);
    expect(clicked).toBe(false);
    await page.$eval('.flyover', flyOver => flyOver.style.left = '0');
    await page.evaluate(() => new Promise(requestAnimationFrame));
    await page.evaluate(() => new Promise(requestAnimationFrame));
    expect(clicked).toBe(false);
    await page.$eval('.flyover', flyOver => flyOver.style.left = '200px');
    await clickPromise;
    expect(clicked).toBe(true);
    expect(await page.evaluate(() => window.result)).toBe('Clicked');
  });
  it('should timeout waiting for hit target', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    const button = await page.$('button');
    await page.evaluate(() => {
      document.body.style.position = 'relative';
      const blocker = document.createElement('div');
      blocker.style.position = 'absolute';
      blocker.style.width = '400px';
      blocker.style.height = '20px';
      blocker.style.left = '0';
      blocker.style.top = '0';
      document.body.appendChild(blocker);
    });
    const error = await button.click({ timeout: 100 }).catch(e => e);
    expect(error.message).toContain('timeout exceeded');
  });
  it('should fail when obscured and not waiting for hit target', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/button.html');
    const button = await page.$('button');
    await page.evaluate(() => {
      document.body.style.position = 'relative';
      const blocker = document.createElement('div');
      blocker.style.position = 'absolute';
      blocker.style.width = '400px';
      blocker.style.height = '20px';
      blocker.style.left = '0';
      blocker.style.top = '0';
      document.body.appendChild(blocker);
    });
    await button.click({ force: true });
    expect(await page.evaluate(() => window.result)).toBe('Was not clicked');
  });
  it('should climb dom for pointer-events:none targets', async({page, server}) => {
    await page.setContent('Click target 
      hi 
      
    `);
    await page.click('button');
    expect(await page.evaluate('window.clicked')).toBe(true);
  });
  it('should fail to click a button animated via CSS animations and setInterval', async({page}) => {
    // This test has a setInterval that consistently animates a button.
    const buttonSize = 10;
    const containerWidth = 500;
    const transition = 100;
    await page.setContent(`
      
      
      
      
      
      
      
    `);
    await page.evaluate(transition => {
      window.setInterval(animateLeft, transition);
      animateLeft();
    }, transition);
    // Ideally, we we detect the button to be continuously animating, and timeout waiting for it to stop.
    // That does not happen though:
    // - Chromium headless does not issue rafs between first and second animateLeft() calls.
    // - Chromium and WebKit keep element bounds the same when for 2 frames when changing left to a new value.
    // This test currently documents our flaky behavior, because it's unclear whether we could
    // guarantee timeout.
    const error1 = await page.click('button', { timeout: 250 }).catch(e => e);
    if (error1)
      expect(error1.message).toContain('timeout exceeded');
    const error2 = await page.click('button', { timeout: 250 }).catch(e => e);
    if (error2)
      expect(error2.message).toContain('timeout exceeded');
  });
  it('should report nice error when element is detached and force-clicked', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/animating-button.html');
    await page.evaluate(() => addButton());
    const handle = await page.$('button');
    await page.evaluate(() => stopButton(true));
    const promise = handle.click({ force: true }).catch(e => e);
    const error = await promise;
    expect(await page.evaluate(() => window.clicked)).toBe(undefined);
    expect(error.message).toContain('Element is not attached to the DOM');
    expect(error.name).toContain('NotConnectedError');
  });
  it('should fail when element detaches after animation', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/animating-button.html');
    await page.evaluate(() => addButton());
    const handle = await page.$('button');
    const promise = handle.click().catch(e => e);
    await page.evaluate(() => stopButton(true));
    const error = await promise;
    expect(await page.evaluate(() => window.clicked)).toBe(undefined);
    expect(error.message).toContain('Element is not attached to the DOM');
    expect(error.name).toContain('NotConnectedError');
  });
  it('should retry when element detaches after animation', async({page, server}) => {
    await page.goto(server.PREFIX + '/input/animating-button.html');
    await page.evaluate(() => addButton());
    let clicked = false;
    const promise = page.click('button').then(() => clicked = true);
    expect(clicked).toBe(false);
    expect(await page.evaluate(() => window.clicked)).toBe(undefined);
    await page.evaluate(() => stopButton(true));
    await page.evaluate(() => addButton());
    expect(clicked).toBe(false);
    expect(await page.evaluate(() => window.clicked)).toBe(undefined);
    await page.evaluate(() => stopButton(true));
    await page.evaluate(() => addButton());
    expect(clicked).toBe(false);
    expect(await page.evaluate(() => window.clicked)).toBe(undefined);
    await page.evaluate(() => stopButton(false));
    await promise;
    expect(clicked).toBe(true);
    expect(await page.evaluate(() => window.clicked)).toBe(true);
  });
  it('should fail when element is blocked on hover', async({page, server}) => {
    await page.setContent(`
    
      Click me 
      
     `);
    const error = await page.click('button', { timeout: 3000 }).catch(e => e);
    expect(error.message).toBe('waiting for element to receive pointer events failed: timeout exceeded');
    expect(await page.evaluate(() => window.clicked)).toBe(undefined);
  });
  it('should wait while element is blocked on hover', async({page, server}) => {
    await page.setContent(`
    
      Click me 
      
     `);
    await page.click('button');
    expect(await page.evaluate(() => window.clicked)).toBe(true);
  });
});
describe('Page.check', function() {
  it('should check the box', async({page}) => {
    await page.setContent(`Text 
`);
    await page.check('label');
    expect(await page.evaluate(() => checkbox.checked)).toBe(true);
  });
  it('should check the box inside label w/o id', async({page}) => {
    await page.setContent(`Text `);
    await page.check('label');
    expect(await page.evaluate(() => checkbox.checked)).toBe(true);
  });
  it('should check radio', async({page}) => {
    await page.setContent(`
      CHECKBOX
      `);
    await page.check('div');
    expect(await page.evaluate(() => checkbox.getAttribute('aria-checked'))).toBe('true');
  });
});