# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from __future__ import absolute_import, unicode_literals

import os
import sys

from mozbuild.base import (
    MachCommandBase,
    MachCommandConditions as conditions,
)

from mach.decorators import (
    CommandProvider,
    Command,
)


def setup_argument_parser():
    from firefox_ui_harness.arguments.base import FirefoxUIArguments
    return FirefoxUIArguments()


def run_firefox_ui_test(tests, testtype=None,
                        binary=None, topsrcdir=None, **kwargs):
    from marionette.runtests import MarionetteHarness
    from mozlog.structured import commandline
    from firefox_ui_harness.cli_functional import FirefoxUITestRunner
    from firefox_ui_harness.arguments import FirefoxUIArguments

    parser = FirefoxUIArguments()
    commandline.add_logging_group(parser)
    args = parser.parse_args()

    if not tests:
        tests = [os.path.join(topsrcdir,
                 'testing/firefox-ui/tests/firefox_ui_tests/manifest.ini')]
    args.tests = tests

    args.binary = binary
    path, exe = os.path.split(args.binary)

    for k, v in kwargs.iteritems():
        setattr(args, k, v)

    parser.verify_usage(args)

    args.logger = commandline.setup_logging("Firefox UI - Functional Tests",
                                            args,
                                            {"mach": sys.stdout})
    try:
        failed = MarionetteHarness(FirefoxUITestRunner,
                                   FirefoxUIArguments,
                                   args=args).run()
        if failed > 0:
            sys.exit(10)
    except Exception:
        args.logger.error('Failure during harness setup', exc_info=True)
        sys.exit(1)
    sys.exit(0)


@CommandProvider
class MachCommands(MachCommandBase):
    @Command('firefox-ui-test', category='testing',
             description='Run Firefox UI functional tests.',
             conditions=[conditions.is_firefox],
             parser=setup_argument_parser,
             )
    def run_firefox_ui_test(self, tests, **kwargs):
        kwargs['binary'] = self.get_binary_path('app')
        return run_firefox_ui_test(tests, topsrcdir=self.topsrcdir, **kwargs)
