from os import path
import json
import pandas as pd 
import csv

#df = pd.read_csv('malware_dataset/malware_API_dataset.csv',header=None,sep='\n') 

if path.exists("apiDict.json"):
    with open('apiDict.json') as json_file: 
        apiDict = json.load(json_file) 

df = pd.DataFrame(list(zip(["0"],["0"],["0"])), columns=[])
fields = ['malware_class','malware_hash','malware_syscall']  
wormFile = "worm_sys_traces.csv"
trojanFile = "trojan_sys_traces.csv"
pupFile = "pup_sys_traces.csv"
misFile = "mis_sys_traces.csv"

with open(wormFile, 'w') as wormFile:
    wormwriter = csv.writer(wormFile)
    wormwriter.writerow(fields) 
    with open (trojanFile, 'w') as trojanFile:
        trojanwriter = csv.writer(trojanFile)
        trojanwriter.writerow(fields) 
        with open (pupFile, 'w') as pupFile:
            pupwriter = csv.writer(pupFile)
            pupwriter.writerow(fields) 
            with open (misFile, 'w') as misFile:
                miswriter = csv.writer(misFile)
                miswriter.writerow(fields) 
                
                df = pd.read_csv('malware_dataset/malware_API_dataset.csv',header=None,sep='\n') 
                df = df[0].str.split(',', expand=True)
                rows = df.shape[0] 
                cols = df.shape[1] 

                for i in range (0,rows):
                    malware_class = df.iat[i,0].strip('"')
                    if ("Worm" in malware_class):
                        malware_class = "Worm"
                        csvwriter = wormwriter
                    elif ("Trojan" in malware_class):
                        malware_class = "Trojan"
                        csvwriter = trojanwriter
                    elif (("Adware" in malware_class) | ("Downloader" in malware_class) | ("WebToolbar" in malware_class)):
                        malware_class = "Pup"
                        csvwriter = pupwriter
                    else:
                        malware_class = "miscellaneous"
                        csvwriter = miswriter

                    malware_hash = df.iat[i,1].strip('"')
                    malware_syscall = ""
                    for j in range (2,cols):
                        val = df.iat[i,j]
                        if df.iat[i,j] != None:
                            val = val.strip('"')
                            if val not in apiDict:
                                last_key = list(apiDict.keys())[-1]
                                apiDict[val] = apiDict[last_key]+1
                                malware_syscall = malware_syscall + str(apiDict[val]) + "_"
                            else:
                                malware_syscall = malware_syscall + str(apiDict[val]) + "_"
                    row = [malware_class, malware_hash, malware_syscall]
                    csvwriter.writerow(row) 