#!/usr/bin/env python

import os
import sys
import fnmatch
import json
import optparse
import logging

def findErrorJsons(dest, foundSoFar=[]):
    """Nothing but a facility comes in handy to get error jsons.

dest -> Destination file/directory. Scans all jsons under this directory (if it is).
foundSoFar -> A list to save all found jsons with error.
RETURN -> The final list contains full pathes of all error jsons."""
    if os.path.isfile(dest) and fnmatch.fnmatch(dest, '*.json'):
        logging.debug('file: %s' % dest)
        if checkOne(dest):
            logging.info('PASSED: [{0}]'.format(dest))
        else:
            logging.info('FAILED: [{0}]'.format(dest))
            foundSoFar.append(os.path.abspath(dest))
        
    elif os.path.isdir(dest):
        logging.debug('dir: %s' % dest)
        for path, subdirs, files in os.walk(dest):
            for f in files:
                fullfile = os.path.join(path, f)
                if fnmatch.fnmatch(fullfile, '*.json'):
                    if checkOne(fullfile):
                        logging.info('PASSED: [{0}]'.format(fullfile))
                    else:
                        logging.info('FAILED: [{0}]'.format(fullfile))
                        foundSoFar.append(fullfile)
                else:
                    logging.debug('skipping: %s' % fullfile)
    
    else:
        logging.debug('skipping: %s' % dest)
    
    return foundSoFar

def checkOne(file):
    jsonfile = open(file)
    
    try:
        json.load(jsonfile)
    except:
        return False
    finally:
        jsonfile.close()
    
    return True

def main():
    usage = "usage: %prog [filename [filename ...]]"
    description = "Nothing but a facility comes in handy to get error jsons."
    optparser = optparse.OptionParser(usage=usage, description=description)
    
    (options, args) = optparser.parse_args()
    logging.debug(args)
    
    errorJsons = []
    if len(args) == 0:
        findErrorJsons("..", errorJsons)
    else:
        for dest in args:
            findErrorJsons(dest, errorJsons)
    
    print('---------------------------------------------')
    if errorJsons:
        logging.info('Got you! %d error json(s) were found! Go take your time: ' % len(errorJsons))
        for file in errorJsons:
            logging.info('    > ' + file)
    else:
        logging.info('Nice one! All passed!')

if __name__ == "__main__":
    # make logs output to studout
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    root.addHandler(ch)
#    sys.argv.append('../components/BASE/config.json')
    main()
