from flask import Blueprint, request, jsonify
from os import path
from oletools import olevba, mraptor
import config

mraptor_bp = Blueprint('mraptor', __name__)

@mraptor_bp.route('/analyze', methods=['POST'])
def analyze_mraptor():
    data = request.form
    file = data['file']
    filepath = path.join(config.Config.FILE_DIRECTORY, file)
    # Analyze with olevba
    vbaparser = olevba.VBA_Parser(filepath)
    if vbaparser.detect_vba_macros():
        vba_code = ''
        try:
            vba_code = vbaparser.get_vba_code_all_modules()
        except Exception as e:
            return jsonify({'error': e})
        raptor = mraptor.MacroRaptor(vba_code)
        raptor.scan()
        if raptor.suspicious:
            return jsonify({'filename': file, 'result': mraptor.Result_Suspicious, 'flags': raptor.get_flags(), 'matches': raptor.matches})
        else: 
            return jsonify({'filename': file, 'result': mraptor.Result_MacroOK, 'flags': raptor.get_flags(), 'matches': raptor.matches})
    else:
        return jsonify({'filename': file, 'result': mraptor.Result_NoMacro})
