#Auto sprite list generator
#Tested in Python 3.6 only!
#The script must be in the same folder with the sprite folders
#Output file: list.txt


import os, sys, re
root_dir = './' + "/".join(re.split('[\\/]', sys.argv[0])[:-1])
asset_dir = "mod_assets/images/s_new"
print(root_dir, asset_dir)

try:
    os.chdir(root_dir)
except:
    print("Wrong_dir:", root_dir)
    exit(1)

def stot(s):
    """Convert a string (without brackets) to a int tuple"""
    
    return tuple(map(int, s.split(',')))

priorities = {
    'bg': 0, #Sprites behind the body (reserved)
    'hc_b': 1, #Haircut back (reserved)
    'b_b' : 2, #Body behind the table
    't': 3, #Table (reserved)
    'f_skin': 4, #Face skin modifactions (e.g. blush)
    'f_mouth': 5, #Mouth
    'f_eyes': 6, #Eyes
    'f_glasses': 7, #Glasses (reserved)
    'hc': 8, #Haircut (reserved)
    'f_brows': 9, #Brows (above the hairs due to the sprite style)
    'hc_f': 10, #Haircut front (for example, a bow; reserved)
    'b_f': 11, #Body front(for example, arms)
    'fg': 12 #Sprites in front of Sayori (reserved)
}

exp_roles = ('b_b', 'f_skin', 'f_mouth', 'f_eyes', 'f_brows')
exp_lists = ([], [], [], [])
exp_list_id = {
    'f_skin': 0,
    'f_mouth': 1,
    'f_eyes': 2,
    'f_brows': 3
}

def is_exp(role):
    """Check if the role is an expression role"""
    return role in exp_roles
   
def get_priority(role):
    """Get sprite priority by it's role"""
    return priorities.get(role) or len(priorities)
    
def read_info_line(line, d):
    """Convert a line of a 'info.txt' file into a list of parameters"""
    line = line.split('#')[0] #Remove comments
    
    if re.fullmatch('\s*', line): #Empty line will be ignored
        return None
    
    
    line = line.split('    ')
    assert len(line) == 4 #Wrong syntax raises an error
    line.append("")
    try:
        line[3], line[4] = line[3].split('@')
        line[4] = line[4][:-1]
    except:
        line[3] = line[3][:-1]
    
    line[0] = "%s/%s/%s" % (asset_dir, d, line[0]) # Ren'Py filename
    
    return line

class Sprite:
    
    def __init__(self, file = "", pos = "(0, 0)", size = "(1, 1)"):
        self.file = file
        self.pos = pos
        self.size = size

    def __str__(self):
        return "%s, %s" % (self.pos, '"%s"' % self.file)
    
    def str_base(self, *add):
        s = "(%s, " % self.size + str(self)
        for i in add:
            s += ', ' + str(i)
        s += ")"
        return s

class Body:
    
    def __init__(self, back, front = None):
        self.back = back
        self.front = front or []
    
    def add_front(self, f):
        self.front.append(f)

    def str_base(self, *add):
        return self.back.str_base(*add, *self.front)

bodies = {}

output = open('new_exp.rpy', 'w')

output.write("## !!! WARRING: THIS LIST WAS AUTO-GENERATED BY create_list.py !!!\n")

for d in os.listdir():
    try:
        info_file = open("./"+d+"/info.txt", "r")
        print("./"+d+"/info.txt is opened.")

        lines = info_file.readlines() 
        for line in lines:
            line = read_info_line(line, d)
            if not line:
                continue
            
            if line[3] == "b_b":
                bodies[line[4]] = Body(Sprite(*line[:3]))
            elif line[3] == "b_f":
                print(line[4], bodies[line[4]].front)
                bodies[line[4]].add_front(Sprite(*line[:3]))
            else:
                try:
                    exp_lists[exp_list_id[line[3]]].append((line[4], Sprite(*line[:3])))
                except:
                    pass
        info_file.close()
        print("./"+d+"/info.txt hase been inspected.")
    except FileNotFoundError:
        pass

for body in bodies:
    print (body)
    output.write("## Body #" + body + '\n')
    for s in exp_lists[0]:
        output.write("## Skin " + s[0] + '\n')
        for m in exp_lists[1]:
            output.write("## Mouth " + m[0] + '\n')
            for e in exp_lists[2]:
                output.write("## Eyes " + e[0] + '\n')
                for b in exp_lists[3]:
                    #print(body+s[0]+m[0]+e[0]+b[0])
                    #print(bodies[body].back.str_base(s[1], m[1], e[1], b[1]))
                    output.write('image sayori ' + body+s[0]+m[0]+e[0]+b[0] + ' = LiveComposite' + bodies[body].str_base(s[1], m[1], e[1], b[1]))
                    output.write('\n')
                output.write('\n')
output.close()