from workflowwebtools.manageactions import *

#first use 'ongorestore -d workflowwebtools -c actions2 actions.bson' command to restore the old data
def get_collection(returnsession=False , uri=None , dbname="workflowwebtools" , collname="actions2"):
    """Gets the actions collection from MongoDB.

    :returns: the actions collection
    :rtype: pymongo.collection.Collection
    """

    if uri:
        client = pymongo.MongoClient(uri, ssl_cert_reqs=ssl.CERT_NONE)
    else:
        client = pymongo.MongoClient()

    coll = getattr( client[dbname] , collname )

    if coll.count() == 0 or 'workflowid' not in list(coll.index_information()):
        coll.create_index([('workflowid', pymongo.TEXT)],
                          name='workflowid', unique=True)

    if returnsession:
        return coll, client.start_session()
    else:
        return coll


def restore():

    actions = get_collection(dbname="workflowwebtools" , collname="actions2") #old actions are backed up here

    newactions,session = get_collection(returnsession=True, dbname="workflowwebtoolsdb" , collname="actions")

    count = 0
    nouser = 0
    notacted = 0
    noaieh = 0
    
    noerrs=0
    nonores=0
    nosuccess=0
    for a in actions.find():
        workflow = a['workflow']
        workflowid = get_workflowid( workflow )
        params = a['parameters']
        reasons = params.get( 'Reasons' , [] )
        aieh = 'AIEH' in reasons
        user = params.get( 'user' , "old")
        if aieh:
            noaieh += 1
            user = "aieh"
        params['user'] = user
        timestamp = a['timestamp']
        acted = a['acted']
        if not acted:
            notacted += 1
        if user == "old":
            nouser += 1        
        count += 1
        if newactions.count_documents({"workflowid":workflowid} , session):
            print("{0} already exists".format( workflow ) )
        else:
            res = None
            try:
                res = newactions.insert_one({'workflowid':workflowid,
                                             'workflow': workflow,
                                             'timestamp': int(timestamp),
                                             'parameters': params,
                                             'acted': 1,
                                             'fromoldconsole':1},
                                            session=session )
            except BaseException as e:
                noerrs += 1
                print("there was an error in inserting the new workflow")
                print(str(e))
                

            if res:
                nosuccess += 1
                continue
            else:
                nonores += 1
                #print('it seeems there was an error in inserting')

        if count % 1000 == 0:
            print(count)
    print( 'nouser:' , nouser )
    print( 'notacted:' , notacted)
    print( 'noaieh:' , noaieh )
    print( 'noerrs:' , noerrs )
    print( 'nonores:' , nonores )
    print( 'nosuccess:' , nosuccess )

if __name__ == '__main__':
    restore()
