#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import (
    absolute_import, division, print_function, unicode_literals)

import requests
import sys
sys.path.append('../riko')

from os import path as p
from importlib import import_module

try:
    # python 3.3+
    from importlib.machinery import SourceFileLoader
except ImportError:
    try:
        # python 3.4+
        from importlib.util import spec_from_file_location, module_from_spec
    except ImportError:
        # python 2.7-
        from imp import load_source as load_file
        io_error = IOError
    else:
        io_error = FileNotFoundError

        def load_file(name, src):
            location = 'examples/%s.py' % src
            spec = spec_from_file_location(name, location)
            module = module_from_spec(spec)
            spec.loader.exec_module(module)
            return module
else:
    io_error = FileNotFoundError
    load_file = lambda name, src: SourceFileLoader(name, src).load_module()

from argparse import RawTextHelpFormatter, ArgumentParser
from riko.bado import react

parser = ArgumentParser(
    description='description: Runs a riko pipe', prog='runpipe',
    usage='%(prog)s [pipeid]', formatter_class=RawTextHelpFormatter)

parser.add_argument(
    dest='pipeid', nargs='?', default=sys.stdin,
    help='The pipe to run (default: reads from stdin).')

parser.add_argument(
    '-a', '--async', action='store_true', default=False,
    help="Load async pipe.\n\n")

parser.add_argument(
    '-t', '--test', action='store_true', default=False,
    help="Run in test mode (uses default inputs).\n\n")

args = parser.parse_args()


def file2name(path):
    return p.splitext(p.basename(path))[0]


def run():
    """CLI runner"""
    try:
        pipeid = args.pipeid.read()
    except AttributeError:
        pipeid = args.pipeid

    try:
        name = file2name('%s.py' % pipeid)
        module = load_file(name, pipeid)
    except io_error:
        try:
            module = import_module('examples.%s' % pipeid)
        except ImportError:
            exit('Pipe examples.%s not found!' % pipeid)

    if args.async:
        pipeline = getattr(module, 'async_pipe')
        react(pipeline, [args.test])
    else:
        pipeline = getattr(module, 'pipe')
        pipeline(test=args.test)

if __name__ == "__main__":
    run()
