#!/usr/bin/env python3

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

varTranslates = {
    'CoatQuality': 'quality',
    'CoatWarm':'warm',
    'coat_description': 'description',
    "CloQuality": 'quality',
    "CloThinness": 'thinness',
    "CloTopCut": 'topcut',
    'CloBra': 'includesBra',
    "CloPanties": 'includesPanties',
    "CloOnePiece": 'isOnepiece',
    "CloInhibit": 'inhibition',
    "CloPantsShortness": "pantsShortness",
    "CloSkirtShortness": 'skirtShortness',
    "CloDress": 'isDress',
    "CloBimbo":'bimbo',
    "CloStyle": 'style',
    "CloStyle2":'style2',
    "CloStyle3":'style3',
    "CloCoverTop":"coverTop",
    "CloCoverBack": "coverBack",
    "CloCoverFront": "coverFront",
    "CloCoverfront": "coverFront",
    "swimwear_description": 'description',
    "ShoStyle": "style",
    "ShoQuality": 'quality',
    "ShoCut": 'cut',
    "ShoHeels": 'heels',
    "BraQuality": 'quality',
    "BraType": 'subtype',
    "BraFun": 'fun',
    "BraCover": 'cover',
    "BraThinness": 'thinness',
    "BraMaterial": 'material',
    "PanType": 'subtype',
    "PanFun": 'fun',
    "PanMaterial": 'material',
    "PanQuality": 'quality',
    "PanThinness": 'thinness',
    'PanCoverBack':'coverBack',
    'PanCoverFront':'coverFront'
}

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]

    with open(destination_filepath, 'w') as file:
        file.write("if(!setup.outfits)\n\tsetup.outfits = {};\n")
        identifier = 'none'
        counter = 0
        for line in lines:
            if match := re.match(r"""^\s*::.*attributes_(.*?)\s*$""",line):
                identifier = match.group(1)
                #file.write("setup.outfits['"+identifier+"'] = {\n")
                file.write("Object.assign(setup.outfits,{\n")
                continue
            if match := re.match(r"""^\s*<<set\s+\$(.*?)\s*=\s*(.*?)>>\s*$""",line):
                varname = match.group(1)
                if(varname in varTranslates):
                    varname = varTranslates[varname]

                val = match.group(2)

                if submatch := re.match(r"""\s*ERROR: FAILED TO CONVERT LITERAL: "{3}'(.*)"{3}\s*""",val):
                    val = f"'{submatch.group(1)}'"

                if len(val) > 2 and val.startswith("'") and val.endswith("'"):
                    #It's a string
                    val = val[1:-1]
                    val = val.replace("'",r"\'")
                    val = f"'{val}'"
                if counter > 0:
                    file.write(f"""\t\t"{varname}": {val},\n""")
                continue
            if match := re.match(r"""^\s*<<(?:else)?if\s+\$location_var\[\$here\]\[1\]\s*==\s*(\d+)\s*>>\s*$""",line):
                id = identifier+'_'+match.group(1)

                idParts = identifier.split('_')
                vendor = idParts[0]
                itemtype = 'error'
                index = match.group(1)
                subtype = None
                if vendor == 'school' or vendor == 'office':
                    subtype = vendor
                    vendor = 'gm'
                    itemtype = 'clothes'
                elif vendor == 'market':
                    itemtype = 'clothes'
                    subtype = 'outfit'
                else:                
                    if(len(idParts) < 2):
                        print("Error: "+destination_filepath)
                    else:
                        itemtype = idParts[1]

                    

                if itemtype == 'coats':
                    itemtype = 'coat'
                    id = id.replace('coats','coat')
                elif itemtype == 'swim':
                    itemtype = 'clothes'
                    if idParts[2] == 'one':
                        subtype = 'swimsuit'
                    else:
                        subtype = 'bikini'
                elif itemtype == 'maid':
                    itemtype = 'clothes'
                    subtype = 'maid'
                elif itemtype in ['outfits']:
                    subtype = itemtype[:-1]
                    id = id.replace(itemtype,itemtype[:-1])
                    itemtype = 'clothes'

                elif itemtype in ['dress','strip','burlesque','cosplay']:
                    subtype = itemtype
                    itemtype = 'clothes'



                if counter > 0:
                    file.write("\t},\n")
                    pass
                file.write("\t'"+id+"':{\n")
                file.write("\t\t'vendor':'"+vendor+"',\n")
                file.write("\t\t'type':'"+itemtype+"',\n")
                if subtype:
                    file.write("\t\t'subtype':'"+subtype+"',\n")
                file.write("\t\t'index':'"+index+"',\n")
                counter += 1


        file.write("\t}\n});")



tw_sources_path = os.path.join("sugarcube","src","outfits")
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])
