#!/usr/bin/env python
from __future__ import print_function

import os
import sys
import argparse
import globals
import toolconfig
import subprocess
import json
from functools import reduce
from globals import UserParamsException

def describeRelease():
    """Asks the user for information describing this software package.
    This is then fed into the .cram/releaseInfo.json and used by the rest of the utilities"""
    appname = os.path.basename(os.path.dirname(os.getcwd()))
    appname = subprocess.check_output(['zenity', '--width=600', '--height=400',
                                    '--entry',
                                    '--title', 'Please enter the name of this software package.',
                                    '--text', 'Name of the software package:',
                                    '--entry-text', appname
                                    ]).decode('utf-8').strip()
    if globals.verbose:
        print(appname)
    apptype = subprocess.check_output(['zenity', '--width=600', '--height=400',
                                    '--list',
                                    '--title', "Choose the type of software application",
                                    '--column="Type"', '--column="Description"']
                                    + list(reduce(lambda x, y: x + y, toolconfig.appTypes.items())) 
                                    ).decode('utf-8').strip()
    if globals.verbose:
        print("Application type is {0}".format(apptype))

    packageInfo = {}
    packageInfo['name'] = appname
    packageInfo['type'] = apptype
    
    if not os.path.exists('.cram'):
        os.makedirs('.cram')
    packageInfofile = os.path.join('.cram', 'packageinfo')
    with open(packageInfofile, 'w') as pkginfof:
        json.dump(packageInfo, pkginfof)
    

def execute(args):
    parser = argparse.ArgumentParser(prog="cram  describe", description="Generate the configuration needed for cram in the current folder. This generates a file .cram/packageinfo that contains a description of this software package that can be used by cram. Currently, this contains a name and an application type")
    parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose logging')
    args = parser.parse_args(args)
    globals.verbose = args.verbose
    try:
        describeRelease()
    except UserParamsException as upe:
        if not globals.verbose and not globals.isunittests:
            print(upe)
            sys.exit(-1)
        else:
            raise

if __name__ == "__main__":
    execute(sys.argv[1:])
