# Copyright 2014 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 time
import urlparse

from telemetry.core import exceptions
from telemetry.internal.actions.drag import DragAction
from telemetry.internal.actions.javascript_click import ClickElementAction
from telemetry.internal.actions.key_event import KeyPressAction
from telemetry.internal.actions.load_media import LoadMediaAction
from telemetry.internal.actions.loop import LoopAction
from telemetry.internal.actions.mouse_click import MouseClickAction
from telemetry.internal.actions.navigate import NavigateAction
from telemetry.internal.actions.page_action import GESTURE_SOURCE_DEFAULT
from telemetry.internal.actions.page_action import SUPPORTED_GESTURE_SOURCES
from telemetry.internal.actions.pinch import PinchAction
from telemetry.internal.actions.play import PlayAction
from telemetry.internal.actions.repaint_continuously import (
    RepaintContinuouslyAction)
from telemetry.internal.actions.repeatable_scroll import RepeatableScrollAction
from telemetry.internal.actions.scroll import ScrollAction
from telemetry.internal.actions.scroll_bounce import ScrollBounceAction
from telemetry.internal.actions.scroll_to_element import ScrollToElementAction
from telemetry.internal.actions.seek import SeekAction
from telemetry.internal.actions.swipe import SwipeAction
from telemetry.internal.actions.tap import TapAction
from telemetry.internal.actions.wait import WaitForElementAction
from telemetry.web_perf import timeline_interaction_record

from py_trace_event import trace_event

import py_utils


_DUMP_WAIT_TIME = 3


class ActionRunner(object):

  __metaclass__ = trace_event.TracedMetaClass

  def __init__(self, tab, skip_waits=False):
    self._tab = tab
    self._skip_waits = skip_waits

  @property
  def tab(self):
    """Returns the tab on which actions are performed."""
    return self._tab

  def _RunAction(self, action):
    action.WillRunAction(self._tab)
    action.RunAction(self._tab)

  def CreateInteraction(self, label, repeatable=False):
    """ Create an action.Interaction object that issues interaction record.

    An interaction record is a labeled time period containing
    interaction that developers care about. Each set of metrics
    specified in flags will be calculated for this time period.

    To mark the start of interaction record, call Begin() method on the returned
    object. To mark the finish of interaction record, call End() method on
    it. Or better yet, use the with statement to create an
    interaction record that covers the actions in the with block.

    e.g:
      with action_runner.CreateInteraction('Animation-1'):
        action_runner.TapElement(...)
        action_runner.WaitForJavaScriptCondition(...)

    Args:
      label: A label for this particular interaction. This can be any
          user-defined string, but must not contain '/'.
      repeatable: Whether other interactions may use the same logical name
          as this interaction. All interactions with the same logical name must
          have the same flags.

    Returns:
      An instance of action_runner.Interaction
    """
    flags = []
    if repeatable:
      flags.append(timeline_interaction_record.REPEATABLE)

    return Interaction(self, label, flags)

  def CreateGestureInteraction(self, label, repeatable=False):
    """ Create an action.Interaction object that issues gesture-based
    interaction record.

    This is similar to normal interaction record, but it will
    auto-narrow the interaction time period to only include the
    synthetic gesture event output by Chrome. This is typically use to
    reduce noise in gesture-based analysis (e.g., analysis for a
    swipe/scroll).

    The interaction record label will be prepended with 'Gesture_'.

    e.g:
      with action_runner.CreateGestureInteraction('Scroll-1'):
        action_runner.ScrollPage()

    Args:
      label: A label for this particular interaction. This can be any
          user-defined string, but must not contain '/'.
      repeatable: Whether other interactions may use the same logical name
          as this interaction. All interactions with the same logical name must
          have the same flags.

    Returns:
      An instance of action_runner.Interaction
    """
    return self.CreateInteraction('Gesture_' + label, repeatable)

  def WaitForNetworkQuiescence(self, timeout_in_seconds=10):
    """ Wait for network quiesence on the page.
    Args:
      timeout_in_seconds: maximum amount of time (seconds) to wait for network
        quiesence unil raising exception.

    Raises:
      py_utils.TimeoutException when the timeout is reached but the page's
        network is not quiet.
    """

    py_utils.WaitFor(self.tab.HasReachedQuiescence, timeout_in_seconds)

  def MeasureMemory(self, deterministic_mode=False):
    """Add a memory measurement to the trace being recorded.

    Behaves as a no-op if tracing is not enabled.

    TODO(perezju): Also behave as a no-op if tracing is enabled but
    memory-infra is not.

    Args:
      deterministic_mode: A boolean indicating whether to attempt or not to
          control the environment (force GCs, clear caches) before making the
          measurement in an attempt to obtain more deterministic results.

    Returns:
      GUID of the generated dump if one was triggered, None otherwise.
    """
    if not self.tab.browser.platform.tracing_controller.is_tracing_running:
      logging.warning('Tracing is off. No memory dumps are being recorded.')
      return None
    if deterministic_mode:
      self.Wait(_DUMP_WAIT_TIME)
      self.ForceGarbageCollection()
      self.Wait(_DUMP_WAIT_TIME)
    dump_id = self.tab.browser.DumpMemory()
    if not dump_id:
      raise exceptions.StoryActionError('Unable to obtain memory dump')
    return dump_id

  def Navigate(self, url, script_to_evaluate_on_commit=None,
               timeout_in_seconds=60):
    """Navigates to |url|.

    If |script_to_evaluate_on_commit| is given, the script source string will be
    evaluated when the navigation is committed. This is after the context of
    the page exists, but before any script on the page itself has executed.
    """
    if urlparse.urlparse(url).scheme == 'file':
      url = self._tab.browser.platform.http_server.UrlOf(url[7:])

    self._RunAction(NavigateAction(
        url=url,
        script_to_evaluate_on_commit=script_to_evaluate_on_commit,
        timeout_in_seconds=timeout_in_seconds))

  def NavigateBack(self):
    """ Navigate back to the previous page."""
    self.ExecuteJavaScript('window.history.back()')

  def WaitForNavigate(self, timeout_in_seconds_seconds=60):
    start_time = time.time()
    self._tab.WaitForNavigate(timeout_in_seconds_seconds)

    time_left_in_seconds = (start_time + timeout_in_seconds_seconds
                            - time.time())
    time_left_in_seconds = max(0, time_left_in_seconds)
    self._tab.WaitForDocumentReadyStateToBeInteractiveOrBetter(
        time_left_in_seconds)

  def ReloadPage(self):
    """Reloads the page."""
    self._tab.ExecuteJavaScript('window.location.reload()')
    self._tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()

  def ExecuteJavaScript(self, *args, **kwargs):
    """Executes a given JavaScript statement. Does not return the result.

    Example: runner.ExecuteJavaScript('var foo = {{ value }};', value='hi');

    Args:
      statement: The statement to execute (provided as a string).

    Optional keyword args:
      timeout: The number of seconds to wait for the statement to execute.
      Additional keyword arguments provide values to be interpolated within
          the statement. See telemetry.util.js_template for details.

    Raises:
      EvaluationException: The statement failed to execute.
    """
    return self._tab.ExecuteJavaScript(*args, **kwargs)

  def EvaluateJavaScript(self, *args, **kwargs):
    """Returns the result of evaluating a given JavaScript expression.

    The evaluation results must be convertible to JSON. If the result
    is not needed, use ExecuteJavaScript instead.

    Example: runner.ExecuteJavaScript('document.location.href');

    Args:
      expression: The expression to execute (provided as a string).

    Optional keyword args:
      timeout: The number of seconds to wait for the expression to evaluate.
      Additional keyword arguments provide values to be interpolated within
          the expression. See telemetry.util.js_template for details.

    Raises:
      EvaluationException: The statement expression failed to execute
          or the evaluation result can not be JSON-ized.
    """
    return self._tab.EvaluateJavaScript(*args, **kwargs)

  def WaitForJavaScriptCondition(self, *args, **kwargs):
    """Wait for a JavaScript condition to become true.

    Example: runner.WaitForJavaScriptCondition('window.foo == 10');

    Args:
      condition: The JavaScript condition (provided as string).

    Optional keyword args:
      timeout: The number in seconds to wait for the condition to become
          True (default to 60).
      Additional keyword arguments provide values to be interpolated within
          the expression. See telemetry.util.js_template for details.
    """
    return self._tab.WaitForJavaScriptCondition(*args, **kwargs)

  def Wait(self, seconds):
    """Wait for the number of seconds specified.

    Args:
      seconds: The number of seconds to wait.
    """
    if not self._skip_waits:
      time.sleep(seconds)

  def WaitForElement(self, selector=None, text=None, element_function=None,
                     timeout_in_seconds=60):
    """Wait for an element to appear in the document.

    The element may be selected via selector, text, or element_function.
    Only one of these arguments must be specified.

    Args:
      selector: A CSS selector describing the element.
      text: The element must contains this exact text.
      element_function: A JavaScript function (as string) that is used
          to retrieve the element. For example:
          '(function() { return foo.element; })()'.
      timeout_in_seconds: The timeout in seconds (default to 60).
    """
    self._RunAction(WaitForElementAction(
        selector=selector, text=text, element_function=element_function,
        timeout_in_seconds=timeout_in_seconds))

  def TapElement(self, selector=None, text=None, element_function=None):
    """Tap an element.

    The element may be selected via selector, text, or element_function.
    Only one of these arguments must be specified.

    Args:
      selector: A CSS selector describing the element.
      text: The element must contains this exact text.
      element_function: A JavaScript function (as string) that is used
          to retrieve the element. For example:
          '(function() { return foo.element; })()'.
    """
    self._RunAction(TapAction(
        selector=selector, text=text, element_function=element_function))

  def ClickElement(self, selector=None, text=None, element_function=None):
    """Click an element.

    The element may be selected via selector, text, or element_function.
    Only one of these arguments must be specified.

    Args: