# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import logging
import os
import sys
import time

from gpu_tests import gpu_integration_test
from gpu_tests import path_util

from telemetry.core import exceptions

data_path = os.path.join(path_util.GetChromiumSrcDir(), 'content', 'test',
                         'data', 'gpu')

wait_timeout = 60  # seconds

harness_script = r"""
  var domAutomationController = {};

  domAutomationController._loaded = false;
  domAutomationController._succeeded = false;
  domAutomationController._finished = false;

  domAutomationController.send = function(msg) {
    msg = msg.toLowerCase();
    if (msg == "loaded") {
      domAutomationController._loaded = true;
    } else if (msg == "success") {
      /* Don't squelch earlier failures! */
      if (!domAutomationController._finished) {
        domAutomationController._succeeded = true;
      }
      domAutomationController._finished = true;
    } else {
      /* Always record failures. */
      domAutomationController._succeeded = false;
      domAutomationController._finished = true;
    }
  }

  domAutomationController.reset = function() {
    domAutomationController._succeeded = false;
    domAutomationController._finished = false;
  }

  window.domAutomationController = domAutomationController;
  console.log("Harness injected.");
"""


class ContextLostIntegrationTest(gpu_integration_test.GpuIntegrationTest):

  _is_asan = False

  @classmethod
  def Name(cls):
    return 'context_lost'

  @classmethod
  def AddCommandlineArgs(cls, parser):
    super(ContextLostIntegrationTest, cls).AddCommandlineArgs(parser)
    parser.add_option(
        '--is-asan',
        help='Indicates whether currently running an ASAN build',
        action='store_true',
        default=False)

  @staticmethod
  def _AddDefaultArgs(browser_args):
    # These are options specified for every test.
    return [
        '--disable-gpu-process-crash-limit',
        # Required to call crashGpuProcess.
        '--enable-gpu-benchmarking',
        # Disable:
        #   Do you want the application "Chromium Helper.app" to accept incoming
        #   network connections?
        # dialogs on macOS. crbug.com/969559
        '--disable-device-discovery-notifications',
    ] + browser_args

  @classmethod
  def GenerateGpuTests(cls, options):
    cls._is_asan = options.is_asan
    tests = (('GpuCrash_GPUProcessCrashesExactlyOncePerVisitToAboutGpuCrash',
              'gpu_process_crash.html'),
             ('ContextLost_WebGLContextLostFromGPUProcessExit',
              'webgl.html?query=kill_after_notification'),
             ('ContextLost_WebGLContextLostFromLoseContextExtension',