import os
from androguard.misc import AnalyzeAPK
import pandas as pd
from pathlib import Path


# <-- Global Variables -->
row = 0


def CSVFormat(path, filename, label):
    
    df = pd.read_csv("permissions.csv")
    new_row = dict.fromkeys(df, 0)    
    new_row[df.columns[0]] = filename
    new_row[df.columns[df.shape[1]-1]] = label
    df = df.append(new_row, ignore_index = True)
    
    try:
        a, d, dx = AnalyzeAPK(r"" + path)
    
        perm_list = []
        perm_list = a.get_permissions()
        
        for col in df.columns:
            for index in perm_list:
                if(col == index):
                    df.loc[row, col] = 1
               

    except Exception:
        print(Exception)

    print(df)
    df.to_csv('permissions.csv', index = False)    

          

def ShiftToCSV():

    data = pd.read_csv('DefaultPermList.txt',sep='\n',header=None)
    data = data.set_index(0).T
    data.to_csv('permissions.csv', index = False)
    

        

def main():
    
    global row
    ShiftToCSV()

    parent_dir = r'F:\FYP CONTENTS\Data\APK Testing Datasets'

    try:
        for subdir, dirs, files in os.walk(parent_dir):
            for file in files:
                if file.endswith(".apk"):
                    label = Path(os.path.join(subdir, file)).parts[-2]
                    CSVFormat(os.path.join(subdir, file), file, label)
                    row += 1
                    continue
                else:
                    print('Skipping file..')
                    continue
                
    except Exception:
        print(Exception)



if __name__ == '__main__':
    main()
  



