#!/usr/bin/env python

import os
import sys
import json
import argparse
from argparse import ArgumentParser
from datetime import datetime, timedelta

from gbp.rpm import SpecFile
from gbp.git.repository import GitRepositoryError
from gbp.errors import GbpError

# set default char-set endcoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8') # pylint: disable-msg=E1101

def unicode_to_str(obj):
    """convert unicode object to str"""

    if isinstance(obj, list):
        return [unicode_to_str(element) for element in obj]
    elif isinstance(obj, dict):
        return {unicode_to_str(key) : unicode_to_str(value) for key, value \
                in obj.iteritems()}
    elif isinstance(obj, unicode):
        return obj.encode('utf-8')
    else:
        return obj

def format_output(data):
    print '-----BEGIN RC OUTPUT-----'
    sys.stdout.flush()
    print data
    sys.stdout.flush()
    print '-----END RC OUTPUT-----'

def parse_specfile(specfile, tag, event, tagger):
    """parse specfile"""

    spec = None

    try:
        # use gbp to parse specfile
        spec = SpecFile(specfile)
    except GbpError, err:
        print 'gbp parse spec failed. %s' % err
        msg = 'The tag %s pushed, but backend service failed to parse %s. \n'\
                'Please try "gbs export" on this tag and make sure it can '\
                'work.\n\n'\
                'Error message:\n'\
                '%s' % (tag, os.path.basename(specfile), err)
        return {'message': msg, 'spec': None}

    return {'message': None, 'spec': spec.name}


def search_main(args):

    resp = parse_specfile(args.specfile, args.tag, None, None)
    format_output(resp)

def argument_parsing(argv):
    """Any arguments passed from user"""

    parser = argparse.ArgumentParser(description='AWS control interface')

    subparsers = parser.add_subparsers(dest='subcommands')

    #### [subcommand - search] ####
    cmd_search = subparsers.add_parser('search')
    cmd_search.add_argument('-f', '--specfile', action='store', dest='specfile', \
                      help='Absolute full path of spec file to be parsed.')
    cmd_search.add_argument('-t', '--tag', action='store', dest='tag', \
                      help='SR tag name.')

    return parser.parse_args(argv[1:])

def main(argv):
    args = argument_parsing(argv)
    if args.subcommands == 'search':
        return search_main(args)
    else:
        print 'Unsopported command %s' % args.subcommands
        return -1

if __name__ == '__main__':
    sys.exit(main(sys.argv))

