from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from rest_framework.parsers import FileUploadParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
# import tensorflow as tf

from .serializers import FileSerializer
from tugas.forms import uploadForm

import pandas as pd
import numpy as np
from androguard import misc
import joblib


# Create your views here.
def index(request):
    return render(request, 'index.html')


def extract(file):
    fs = FileSystemStorage()
    android_manifest_permission = pd.read_csv(fs.path('manifestPermissionAndroid.csv'))
    android_manifest_permission['class'] = 'Miscellaneous'
    android_groups_permission = pd.read_csv(fs.path('permissionGeneral.csv'))
    android_general_permission = android_groups_permission.append(android_manifest_permission).drop_duplicates(
        subset='name').reset_index(drop=True)
    normal_permission = android_general_permission.loc[android_general_permission['class'] == 'Normal']
    signature_permission = android_general_permission.loc[android_general_permission['class'] == 'Signature']
    dangerous_permission = android_general_permission.loc[android_general_permission['class'] == 'Dangerous']
    dataResult = pd.DataFrame()

    a, d, dx = misc.AnalyzeAPK(file)
    appname = a.get_app_name()
    input_apk_permission = a.get_permissions()
    listOfInputApkPermission = [['Permission']]
    listOfInputApkPermission.append(','.join(input_apk_permission))
    headers = listOfInputApkPermission.pop(0)
    dfData = pd.DataFrame(listOfInputApkPermission, columns=headers)
    detected = dfData.fillna('')
    zeroDataframe = pd.DataFrame({0: 0}, index=[0])
    for index, row in detected.iterrows():

        dfAPKPermission = pd.DataFrame(row[0].split(sep=','))
        dfAPKPermission.columns = ['name']

        normal_counter = normal_permission.name.isin(dfAPKPermission.name).to_frame().name.value_counts().to_frame()
        normal_counter = normal_counter.drop([False]).reset_index(drop=True)
        normal_counter.columns = [0]
        if normal_counter.empty:
            normal_counter = zeroDataframe

        # Signature
        signature_counter = signature_permission.name.isin(
            dfAPKPermission.name).to_frame().name.value_counts().to_frame()
        signature_counter = signature_counter.drop([False]).reset_index(drop=True)
        signature_counter.columns = [0]
        if signature_counter.empty:
            signature_counter = zeroDataframe

        # Dangerous
        dangerous_counter = dangerous_permission.name.isin(
            dfAPKPermission.name).to_frame().name.value_counts().to_frame()
        dangerous_counter = dangerous_counter.drop([False]).reset_index(drop=True)
        dangerous_counter.columns = [0]
        if dangerous_counter.empty:
            dangerous_counter = zeroDataframe

        dataResult = dataResult.append(normal_counter). \
            append(signature_counter). \
            append(dangerous_counter).transpose()

    return dataResult



class FileUploadView(APIView):
    parser_class = (FileUploadParser,)

    def post(self, request, *args, **kwargs):

        file_serializer = FileSerializer(data=request.data)
        statuss = ""
        malware = ""
        if file_serializer.is_valid():
            # get the apk
            file_input = request.data['file']
            fs = FileSystemStorage()
            file = fs.save('test.apk', file_input)

            # Extract APK File
            df = extract(fs.path(file))
            X = df.values.tolist()


            # Test Data
            load_model = joblib.load(fs.path('ModelTA05.dat'))
            y_pred = load_model.predict(X)
            result = [round(value) for value in y_pred]
            result = result[0]

            if result == 0:
                statuss = "Berbahaya"
                malware = "Backdoor "
            elif result == 1:
                statuss = "Berbahaya"
                malware = "DangerousObject"
            elif result == 2:
                statuss = "Berbahaya"
                malware = "Exploit"
            elif result == 3:
                statuss = "Tidak Berbahaya"
                malware = "NonMalware"
            elif result == 4:
                statuss = "Berbahaya"
                malware = "RiskTool"
            elif result == 5:
                statuss = "Berbahaya"
                malware = "Trojan"
            elif result == 6:
                statuss = "Berbahaya"
                malware = "Trojan-Banker"
            elif result == 7:
                statuss = "Berbahaya"
                malware = "Trojan-Clicker"
            elif result == 8:
                statuss = "Berbahaya"
                malware = "Trojan-Downloader"
            elif result == 9:
                statuss = "Berbahaya"
                malware = "Trojan-Dropper"
            elif result == 10:
                statuss = "Berbahaya"
                malware = "Trojan-FakeAV"
            elif result == 11:
                statuss = "Berbahaya"
                malware = "Trojan-SMS"
            elif result == 12:
                statuss = "Berbahaya"
                malware = "Trojan-Spy"


            fs.delete(file)

            result = {
                    'status': statuss,
                    'malware_name': malware,
                }

            return Response(result, status=status.HTTP_201_CREATED)
        else:
            return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

