# -*- coding: utf_8 -*-
import logging
import os

from django.conf import settings

logger = logging.getLogger(__name__)


def apkid_analysis(app_dir, apk_file, apk_name):
    """APKID Analysis of DEX files."""
    if not settings.APKID_ENABLED:
        return {}
    try:
        import apkid
    except ImportError:
        logger.error('APKiD - Could not import APKiD')
        return {}
    if not os.path.exists(apk_file):
        logger.error('APKiD - APK not found')
        return {}

    apkid_ver = apkid.__version__
    from apkid.apkid import Scanner, Options
    from apkid.output import OutputFormatter
    from apkid.rules import RulesManager

    logger.info('Running APKiD %s', apkid_ver)
    options = Options(
        timeout=30,
        verbose=False,
        entry_max_scan_size=settings.DATA_UPLOAD_MAX_MEMORY_SIZE,
        recursive=True,
    )
    output = OutputFormatter(
        json_output=True,
        output_dir=None,
        rules_manager=RulesManager(),
        include_types=False,
    )
    rules = options.rules_manager.load()
    scanner = Scanner(rules, options)
    res = scanner.scan_file(apk_file)
    try:
        findings = output._build_json_output(res)['files']
    except AttributeError:
        # apkid >= 2.0.3
        try:
            findings = output.build_json_output(res)['files']
        except AttributeError:
            logger.error('yara-python dependency required by '
                         'APKiD is not installed properly. '
                         'Skipping APKiD analysis!')
            findings = {}
    sanitized = {}
    for item in findings:
        filename = item['filename']
        if '!' in filename:
            filename = filename.split('!', 1)[1]
        sanitized[filename] = item['matches']
    return sanitized
