from sqlalchemy.orm import sessionmaker, scoped_session

from lib.model.database.Database import Database
from .lib.DexClassLoader import DexClassLoader
import logging
import os


current_path = os.path.dirname(os.path.realpath(__file__))

def onload():
    logging.debug("DexClassLoader:loaded()")

def onunload():
    logging.debug("DexClassLoader:unloaded()")

def parse(module, message, data):
    if(message['plugin'] == 'dexclassloader'):

        # Create a thread local session
        engine = Database.get_engine()

        session_factory = sessionmaker(bind=engine)
        Session = scoped_session(session_factory)
        session = Session()
        Session.remove()

        # Fetch application for this session ( could not use self.application
        # because the usage must be thread local )
        dexclassloader = DexClassLoader(message['dexPath'], message['optimizedDirectory'], message['librarySearchPath'], message['parent'], message['entrypoint'], message['stack'])
        dexclassloader.application_id = module.application.id
        logging.debug(repr(dexclassloader))

        query = session.query(DexClassLoader).filter(DexClassLoader.application_id==module.application.id).filter(DexClassLoader.dexPath==dexclassloader.dexPath).filter(DexClassLoader.optimizedDirectory==dexclassloader.optimizedDirectory).filter(DexClassLoader.librarySearchPath==dexclassloader.librarySearchPath).filter(DexClassLoader.parent==dexclassloader.parent).filter(DexClassLoader.entrypoint==dexclassloader.entrypoint)

        resultQuery = query.all()
        
        if len(resultQuery) == 0:
            session.add(dexclassloader)
            session.commit()

def get_frida_script():
    logging.debug("DexClassLoader:get_frida_script()")
    with open(f"{current_path}/frida.js") as f:
        return ("DexClassLoader", f.read())