# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-

#
# Ubuntu Core Webapps
# Copyright (C) 2015 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import shutil
import subprocess

from autopilot import (
    get_test_configuration,
    testcase
)
from selenium import webdriver
from selenium.webdriver.chrome import options
from ubuntuuitoolkit import fixture_setup

import amazon_webapp


DESKTOP_FILE_NAME = 'webapp-amazon.desktop'

DEFAULT_IMPLICIT_WAIT = 10  # seconds


def get_source_desktop_file_path():
    return os.path.join(
        os.path.dirname(amazon_webapp.__file__), '..', '..', '..',
        DESKTOP_FILE_NAME)


def get_local_desktop_file_directory():
    return os.path.join(
        os.environ.get('HOME'), '.local', 'share', 'applications')


def get_chrome_driver_path():
    env = os.environ.copy()
    readonly_dependencies_path = get_readonly_dependencies_path()
    if readonly_dependencies_path:
        # XXX When running with adt-run, this is needed if the image is
        # read-only so we can find the chromium driver path.
        env['PERL5LIB'] = os.path.join(
            readonly_dependencies_path, 'usr', 'share', 'perl5')

    architecture = subprocess.check_output(
        ['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
        env=env, universal_newlines=True).strip()

    chrome_driver_path = '/usr/lib/{}/oxide-qt/chromedriver'.format(
        architecture)

    if readonly_dependencies_path and not os.path.exists(chrome_driver_path):
        # Try the read-only install path.
        chrome_driver_path = os.path.join(
            readonly_dependencies_path, chrome_driver_path.lstrip('/'))

    return chrome_driver_path


def get_readonly_dependencies_path():
    adt_artifacts_path = os.environ.get('ADT_ARTIFACTS', None)
    if adt_artifacts_path:
        return os.path.join(os.path.dirname(adt_artifacts_path), 'deps')
    else:
        return None


class AmazonWebappTestCase(testcase.AutopilotTestCase):

    DEFAULT_WEBVIEW_INSPECTOR_IP = '127.0.0.1'
    DEFAULT_WEBVIEW_INSPECTOR_PORT = 9221

    def setUp(self):
        super().setUp()
        self.setup_webdriver_environment()

    def setup_webdriver_environment(self):
        self.useFixture(fixture_setup.InitctlEnvironmentVariable(
            global_=True,
            UBUNTU_WEBVIEW_DEVTOOLS_HOST=self.DEFAULT_WEBVIEW_INSPECTOR_IP,
            UBUNTU_WEBVIEW_DEVTOOLS_PORT=str(
                self.DEFAULT_WEBVIEW_INSPECTOR_PORT)
        ))

    def launch_application(self):
        if (get_test_configuration().get('from_source', None) and
                os.path.exists(get_source_desktop_file_path())):
            return self.launch_application_from_source()
        else:
            return self.launch_installed_application()

    def launch_application_from_source(self):
        test_desktop_file_path = os.path.join(
            get_local_desktop_file_directory(), 'webapps-test.desktop')
        shutil.copy(get_source_desktop_file_path(), test_desktop_file_path)
        self.addCleanup(os.remove, test_desktop_file_path)

        return self.launch_upstart_application('webapps-test')

    def launch_installed_application(self):
        return self.launch_click_package(
            'com.ubuntu.developer.webapps.webapp-amazon')

    def get_webdriver(self):
        driver_options = options.Options()
        driver_options.binary_location = ''
        driver_options.debugger_address = '{}:{}'.format(
            self.DEFAULT_WEBVIEW_INSPECTOR_IP,
            self.DEFAULT_WEBVIEW_INSPECTOR_PORT)
        driver = webdriver.Chrome(
            executable_path=get_chrome_driver_path(),
            chrome_options=driver_options
        )

        self.assertIsNot(driver, None)

        self.addCleanup(self.close_webdriver, driver)

        driver.implicitly_wait(DEFAULT_IMPLICIT_WAIT)
        return driver

    def close_webdriver(self, driver):
        driver.close()
        driver.quit()

    def test_search_in_amazon_must_show_results(self):
        proxy = self.launch_application()
        driver = self.get_webdriver()

        amazon = amazon_webapp.AmazonMainPage(proxy, driver)
        results_page = amazon.search('Test')

        results = results_page.get_search_results_count_label()
        self.assertTrue(
            results.endswith('results for "Test"') or
            results.endswith('Results'))
