import os
import sys
import json
import copy
import getopt
from InstallConfigItemResolver import ConfigItemLocator
from InstallConfigItemResolver import InstallConfigItemPathResolver
from InstallConfigItemResolver import InstallScriptsPathResolver
from InstallConfigItemResolver import InstallDataPatchSqlFilePathResolver
from InstallConfigItemResolver import InstallConfigFileDirResolver

class InstallConfigFileItemDetector(object):
    FILE_ITEMS = InstallConfigItemPathResolver.RESOLVE_ITEMS + InstallScriptsPathResolver.RESOLVE_ITEMS + InstallDataPatchSqlFilePathResolver.RESOLVE_ITEMS + [InstallConfigFileDirResolver.CONFIG_FILE_DIRS, InstallConfigFileDirResolver.CONFIG_FILE_TODELETE_DIRS]
    
    def __init__(self, config):
        if type(str()) == type(config):
            json_data = open(config)
            self.config = json.load(json_data)
            json_data.close()
        else:
            self.config = config
    
    def detectPaths(self):
        for itemAttributeTree in self.FILE_ITEMS:
            ConfigItemLocator().locateItemsAndExcute(itemAttributeTree, self.config, self)
            
    def execute(self, locatedItem, lastAttributeName):
        if type(dict()) == type(locatedItem):
            if locatedItem.has_key(lastAttributeName) and locatedItem[lastAttributeName]:
                if type(list()) == type(locatedItem[lastAttributeName]):
                    for i in range(0,len(locatedItem[lastAttributeName])):
                        self.checkFileExists(locatedItem[lastAttributeName][i])
                elif isinstance(locatedItem[lastAttributeName], basestring):
                    self.checkFileExists(locatedItem[lastAttributeName])
        elif type(list()) == type(locatedItem):
            for item in locatedItem:
                self.execute(item, lastAttributeName)
    
    def checkFileExists(self, filePath):
        print "checking File: " + filePath
        if not os.path.exists(filePath):
            print "ERROR: File " + filePath + " can not be resolved!!"
        else:
            print "OK" 

def main():
    inputfile = ""
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:v", ["help","ifile"])
    except getopt.GetoptError as err:
        print "InstallConfigFileItemDetector.py -i inputfile" + str(err)
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            print "InstallConfigFileItemDetector.py -i <inputfile>"
            sys.exit(0)
        elif o in ("-i", "--ifile"):
            inputfile = a
    try:
        detector = InstallConfigFileItemDetector(inputfile)
        detector.detectPaths()
    except KeyboardInterrupt:
        print ''
        print '<CTRL>-C detected...Exiting...'
            
if __name__ == "__main__":
    main()    
