#!/usr/bin/env python

#
# Copyright 2017 Tubular Labs, Inc.
#
# 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.
#

import argparse
import logging
import sys
import textwrap

from sparkly.instant_testing import InstantTesting


logging.basicConfig(
    stream=sys.stderr,
    level=logging.INFO,
    format='%(levelname)s %(message)s',
)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=textwrap.dedent(
            """\
            Sparkly Instant Testing.
            
            The tool speeds up iterative development on spark-based tests.
            It keeps JVM with initialised SparkContext running between multiple test sessions.
             
            Usage:
                sparkly-testing up
                py.test path/to/test_integration_with_pyspark.py  # slow (first run)
                py.test path/to/test_integration_with_pyspark.py  # fast (next runs)
                sparkly-testing down
                
            To change SparkContext options or to add new jars/packages call:
                sparkly-testing refresh
            """,
        )
    )

    sub_commands = parser.add_subparsers()

    # Instant testing mode.
    sub_commands.add_parser(
        name='up',
        help='Activate instant testing mode.',
    ).set_defaults(func=lambda _: InstantTesting.activate())

    sub_commands.add_parser(
        name='down',
        help='Deactivate instant testing mode.',
    ).set_defaults(func=lambda _: InstantTesting.deactivate())

    sub_commands.add_parser(
        name='refresh',
        help='Refresh SparkContext options or add new jars/packages.',
    ).set_defaults(func=lambda _: InstantTesting.deactivate() or InstantTesting.activate())

    args = parser.parse_args()

    if hasattr(args, 'func'):
        args.func(args)
    else:
        parser.print_help()
