'''Displays the history of upgrades for an IOC/HLA application'''
from __future__ import print_function

import fnmatch
import os
import sys
import argparse
import globals
import toolconfig
import multi_facility_process_helper_client
import json
import listCurrentReleases
from globals import UserParamsException
from six import iteritems

def printChanges(ioc, changes, count, chars):
    if len(changes) <=0:
        return
    print(ioc)
    if count < 0:
        count = len(changes)
    for change in changes[:count]:
        change_line = "--> {0} on {1} by {2}".format(change['release'], change['datetime'], change['user'])
        if 'message' in change:
            # Truncate message if needed
            if len(change['message']) > chars:
                change_line += " ({0}...)".format(change['message'][:chars])
            else:
                change_line += " ({0})".format(change['message'][:chars])
        print(change_line)

def displayHistory(name, type, count, chars, searchioc):
    '''Displays the history of upgrades for an IOC/HLA application
    count controls the number of entries displayed per IOC/HLA application
    chars controls the number of characters displayed per message
    searchioc filters by IOC name (wildcards *, ? allowed)
    '''
    for facility in toolconfig.getListOfFacilities():
        arg = {}
        arg['name'] = name
        arg['type'] = type
        arg['releaseFolder'] = toolconfig.getConfigForFacility(facility)[type]['releaseFolder']
        commandsAndArgs = []
        commandsAndArgs.append(('hist', arg))
        results = multi_facility_process_helper_client.executeCommandsOnFacility(facility, commandsAndArgs)
        if not results[0]:
            print("No history available for {0} of type {1} in {2}".format(name, type, facility))
            continue
        histdict = results[0]
        print("History of changes to {0} in facility:\033[1;31m {1} \033[0m".format(name, facility))
        if 'MASTER' in histdict and searchioc == '*':
            # Show history of master releases only if IOC pattern is not specified
            printChanges('MASTER' if type in ['SIOC', 'HIOC'] else name, histdict['MASTER'], count, chars)
        for ioc, changes in iteritems(histdict):
            if ioc != 'MASTER' and fnmatch.fnmatch(ioc, searchioc):
                printChanges(ioc, changes, count, chars)


def execute(args):
    parser = argparse.ArgumentParser(prog="cram history")
    parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose logging')
    parser.add_argument('-n', '--name', help='Specify the application name; we automatically pick this up from the package info if we are running this command in the folder containing the release')
    parser.add_argument('-t', '--type', help='Specifies the type of application from the deployment perspective. Possible values are ' + ", ".join(toolconfig.appTypes.keys()))
    parser.add_argument('-c', '--count', help='How many entries we want displayed per IOC/HLA application?', default=-1, type=int)
    parser.add_argument('-l', '--limit-chars', help='How many characters we want displayed per comment?', default=80, type=int)
    parser.add_argument('-i', '--ioc', help='Search pattern for IOCs. Supported wildcards are * and ?. Quote pattern to prevent globbing.', default='*')

    args = parser.parse_args(args)
    globals.verbose = args.verbose
    count = args.count
    chars = args.limit_chars
    searchioc = args.ioc
    packageInfo = toolconfig.determinePackageInfoFromArgs(args)
    name = packageInfo['name']
    type = packageInfo['type']
    try:
        displayHistory(name, type, count, chars, searchioc)
    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:])

