import pandas as pd
import numpy as np
import sklearn
import warnings
import unittest
from sklearn.model_selection import train_test_split
from keras.layers import Input, Dense
from keras.models import Model, load_model
from dbn.tensorflow import SupervisedDBNClassification
from dbn.models import UnsupervisedDBN
from sklearn.svm import SVC, LinearSVC, NuSVR
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report, accuracy_score
from imports import *
from preTest import *


#Function for classify apk file

def classify(apk, data):
    a,d,dx = AnalyzeAPK(apk)
    if int(a.valid_apk) == 0:
        return 0
    feats = list()

    feats += (data.makeHotVector([data.vocabPerm.index(p) for p in a.get_permissions() if p in data.vocabPerm], \
                                    data.vocabLengths["perm"])).tolist()
    feats += (data.makeHotVector([data.vocabServ.index(p) for p in a.get_services() if p in data.vocabServ], \
                                    data.vocabLengths["serv"])).tolist()
    feats += (data.makeHotVector([data.vocabRecv.index(p) for p in a.get_receivers()if p in data.vocabRecv], \
                                    data.vocabLengths["recv"])).tolist()
    test_feats = np.array(feats)
    test_feats = test_feats.reshape((-1, 1))
    #print(test_feats)
    loaded_encoder = load_model("pickled/autoEncoder.mod", compile=False)
    loaded_encoder.compile(optimizer='adadelta', loss='categorical_crossentropy')
    test_feats_with_reduced_dimension = loaded_encoder.predict(test_feats.T)

    f = open("pickled/DBNClassifier.pkl", "rb")
    classifier = pickle.load(f)
    f.close()
    res_predict = classifier.predict(test_feats_with_reduced_dimension)
    print("+-------------------------------------------------------------------------")
    print("| Given APK file: ", apk)

    if res_predict == [0]:
        print ("| => The APK file is Malign")
    else:
        print ("| => The APK file is Bengin")
    print("|_________________________________________________________________________")

def TESTFILE(filename):
    fs = filename.split(",")
    data = PreTest()
    for f in fs:
        classify(f, data)

def TESTFOLDER(foldername):
    data = PreTest()
    print("[*] Given folder: ", foldername)
    for i in glob.glob(foldername + "/*.apk"):
        classify(i, data)
