import pickle

def pickleApplication(applicationPath,destinationPath=None):
    import os
    from imp import load_source

    if destinationPath is None:
        destinationPath=os.path.join(os.path.normpath(applicationPath),'application','pckapp')
    """ Remove all the files in pckapp directory if pckapp exists already """
    if os.path.exists(destinationPath):
        for root, dirs, files in os.walk(destinationPath):
            for f in files:
                os.unlink(os.path.join(root, f))
    else:
        os.mkdir(destinationPath)
    app_module=load_source('Application', os.path.join(applicationPath,'application','Application.py'))
    file = open(os.path.join(destinationPath,'Application'+".pck"),"wb")
    pickle.dump(app_module.Application, file,1)
    file.close()
    form_module=load_source('formmapping', os.path.join(applicationPath,'application','formmapping.py'))
    file = open(os.path.join(destinationPath,'formmapping'+".pck"),"wb")
    pickle.dump(form_module.formMapping, file,1)
    file.close()
    action_module=load_source('actionmapping', os.path.join(applicationPath,'application','actionmapping.py'))
    file = open(os.path.join(destinationPath,'actionmapping'+".pck"),"wb")
    pickle.dump(action_module.actionMapping, file,1)
    file.close()
    import_module=load_source('importmapping', os.path.join(applicationPath,'application','importmapping.py'))
    file = open(os.path.join(destinationPath,'importmapping'+".pck"),"wb")
    pickle.dump(import_module.importMapping, file,1)
    file.close()
    index_module=load_source('rdbms_indexes', os.path.join(applicationPath,'application','rdbms_indexes.py'))
    file = open(os.path.join(destinationPath,'rdbms_indexes'+".pck"),"wb")
    pickle.dump(index_module.rdbms_indexes, file,1)
    file.close()
    for sheetId in app_module.Application[app_module.Application['root']]['Application.SheetMetadata']:
        sheet_module=load_source(sheetId, os.path.join(applicationPath,'application',sheetId+'.py'))
        file = open(os.path.join(destinationPath,sheetId+".pck"),"wb")
        cmd='root=sheet_module.'+sheetId
        exec cmd
        pickle.dump(root, file,1)
        file.close()

def unpickle(filepath,filename=None):
    import os
    filepath=os.path.join(os.path.dirname(__file__),'orangescape','application')
    import appconfig as config
    if config.env==config.SL:
        filepath=filename
    elif filename is not None:    	
        filepath=os.path.join(filepath,filename)
    pickled_file = open(filepath,"rb")
    org_file = pickle.load(pickled_file)
    return org_file
