#!/usr/bin/env python3

import os
from glob import glob
import fileinput
import re
import sys

def file_convert(filename):
    global tw_sources_path, tw_destination_path
    source_filepath= os.path.join(tw_sources_path,filename)+'.tw'
    destination_filepath= os.path.join(tw_destination_path,filename)+'compiled.js'
    with open(source_filepath, 'r') as file:
        lines = [line.rstrip() for line in file]

    npccounter = 0

    with open(destination_filepath, 'w') as file:
        file.write("if(!setup.beverages)\n\tsetup.beverages = {};\n")
        identifier = ''
        counter = 0
        for line in lines:
            if match := re.match(r"""\s*<<(?:else)?if\s+\$location_var\[\$here\]\[0\]\s*==\s*'(.*?)'\s*>>\s*""",line):
                if identifier != '':
                    if hydra_inc > 0:
                        file.write(f"\thydra_inc: {hydra_inc},\n")
                    elif hydra_dec > 0:
                        file.write(f"\thydra_dec: {hydra_dec},\n")
                    file.write("}\n")
                identifier = match.group(1)
                file.write("setup.beverages['"+identifier+"'] = {\n")
                hydra_inc = 0
                hydra_dec = 0
                continue
            elif identifier != '':
                if match := re.search(r"""<<set(?:init)?\s+(.*?)\s*([+-]?)=\s*(.*?)>>""",line):
                    var = match.group(1)
                    val = match.group(3)
                    suffix = ''
                    if(match.group(2) == '+'):
                        suffix = '_inc'
                    if(match.group(2) == '-'):
                        suffix = '_dec'
                    if(var.startswith('$pc.')):
                        var = var[4:]
                    if(var.startswith('pcs_')):
                        var = var[4:]
                    if(var.startswith('$time.')):
                        var = var[6:]
                    if(var == '$finances.cash'):
                        var = 'cash'
                        val = '0'
                    if(var == '$cumspclnt'):
                        var = 'cumclean'
                    if(var == '$boozeVar'):
                        var = 'booze'
                    if(var == "teeth['caffe_or_tea']"):
                        var = 'teeth_caffe_or_tea'
                    var += suffix

                    if(var == 'hydra_inc'):
                        hydra_inc = max(int(val),hydra_inc)
                    elif(var == 'hydra_dec'):
                        hydra_dec = max(int(val),hydra_dec)
                    else:
                        file.write(f"\t{var}: {val},\n")
                elif match := re.search(r"""<<gs\s+'drugs'\s+'alcohol'\s*('\w+')\s*>>""",line):
                    alco = match.group(1)
                    file.write(f"\talcohol: {alco},\n")
                elif match := re.search(r"""<<image\s+"(.*?)"\s*>>""",line):
                    image =match.group(1)
                    file.write(f'\timage: "{image}",\n')
                elif match := re.search(r"""<<image\s+`'(?:images/)?(.*?)'\s*\+\s*rand\((\d+)\s*,\s*(\d+)\s*\)\s*\+\s*'(.*?)'`\s*>>""",line):
                    image = match.group(1) + '#' + match.group(4)
                    rand0 = match.group(2)
                    rand1 = match.group(3)
                    file.write('\timageRand: {template:"'+image+'",min:'+rand0+',max:'+rand1+'},\n')

        file.write("}\n")



tw_sources_path = os.path.join("sugarcube","src","autogenerated","beverage")
tw_destination_path = os.path.join(tw_sources_path,"compiled")

os.makedirs(tw_destination_path,exist_ok=True)

filesNames = [y for x in os.walk(tw_sources_path) for y in glob(os.path.join(x[0], '*.tw'))]
#print(filesNames)
for file in filesNames:
    #print(file)
    file_convert(os.path.basename(file).split('.')[0])
