#!/usr/bin/env python3.8

import sys
import os
import argparse
import json

import logging
logging.basicConfig( level = logging.INFO )

directory = r'..\mguns\src\shared\weapons'
weaponDefPaths = []
weaponDefs = []

# each def is a key:value with the value including a prefix to handle variables declared with DEFINE and such
wepValuesDef = {
    "wep.displayname" : ["0", ""],
    "wep.magazine_capacity" : ["0", ""],
    "wep.recoil_cooldown" : ["0", ""],
    "wep.recoil_max" : ["0", ""],
    "_RANGE" : ["0", "#define"],
    "_SPREAD" : ["0", "#define"],
    "_SPREAD_BASE" : ["0", "#define"],
    "_SPREAD_MAX" : ["0", "#define"],
    "shot.dmg_value" : ["0", ""],
    "shot.dmg_flags" : ["0", ""],
    "shot.dmg_knock" : ["0", ""]
}

class weaponDef:
    def __init__(self, name):
        self.name = name
        self.wepValues = {}
        
def FindValueFromKeyInLines(lines, key):
    for line in lines:
        if line.find(key) != -1 and wepValuesDef[key][1] == "": #matches on "x = y" assignments
            return line[line.find("=") + 2:line.find(";")] #I guess this could break if line wrapping/continuation is used
        elif line.find(key) != -1 and line.find(wepValuesDef[key][1]) != -1: #matches on lines containing the extra prefix
            return line[line.rindex(" ")+1 : -1] #gets the end of the line

def to_json(obj):
    return json.dumps(obj, default=lambda obj: obj.__dict__, indent=4, sort_keys=True)

if ( __name__ == '__main__' ):

    for entry in os.scandir(directory):
        if (entry.path.endswith(".qc") and entry.is_file()):
            weaponDefPaths.append(entry)
    for weaponEntry in weaponDefPaths:
        if (weaponEntry.name != "w_defs.qc" and weaponEntry.name != "w_main.qc" ): #don't parse the defs or main file lol
            reader = open(weaponEntry.path, "r")
            try:
                readerLines = reader.readlines()
                aWeaponDef = weaponDef(weaponEntry.name[weaponEntry.name.find("w_")+2:weaponEntry.name.find(".qc")]) #parse out name from filename
                for wepValue in wepValuesDef:
                    aWeaponDef.wepValues[wepValue] = FindValueFromKeyInLines(readerLines, wepValue) #replace values in the new object with values found in the file
                weaponDefs.append(aWeaponDef)
            finally:
                reader.close()
    f = open("weaponDefs.json", "w")
    f.write(to_json(weaponDefs))
    f.close()