#    Copyright 2012-2015 ARM Limited
#
# 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.
#
# pylint: disable=E1101,W0201
import os
import time
import urllib
import tarfile
import shutil
import json
import re

from collections import defaultdict

from wlauto import settings, Workload, Parameter, Alias, Executable
from wlauto.exceptions import ConfigError, WorkloadError
from wlauto.utils.types import boolean

DEFAULT_BBENCH_FILE = "http://bbench.eecs.umich.edu/bbench/bbench_2.0.tgz"
DOWNLOADED_FILE_NAME = "bbench_2.0.tgz"
BBENCH_SERVER_NAME = 'bbench_server'
PATCH_FILES = os.path.join(os.path.dirname(__file__), "patches")
DEFAULT_AUDIO_FILE = "http://archive.org/download/PachelbelsCanoninD/Canon_in_D_Piano.mp3"
DEFAULT_AUDIO_FILE_NAME = 'Canon_in_D_Piano.mp3'


class BBench(Workload):

    name = 'bbench'
    description = """
    BBench workload opens the built-in browser and navigates to, and
    scrolls through, some preloaded web pages and ends the workload by trying to
    connect to a local server it runs after it starts. It can also play the
    workload while it plays an audio file in the background.

    """

    summary_metrics = ['Mean Latency']

    parameters = [
        Parameter('with_audio', kind=boolean, default=False,
                  description=('Specifies whether an MP3 should be played in the background during '
                               'workload execution.')),
        Parameter('server_timeout', kind=int, default=300,
                  description='Specifies the timeout (in seconds) before the server is stopped.'),
        Parameter('force_dependency_push', kind=boolean, default=False,