import os
import re

import utils

cur_dir = os.path.dirname(__file__)

def parse(db):
    count = 1
    csv_roots = ["steam", "diesel", "electric", "dmu",
                 "emu", "metro", "coach", "wagon"]
    readers = [utils.csv_to_reader(os.path.join(cur_dir, "csv", c + ".csv")) \
               for c in csv_roots]
    for root, reader in zip(csv_roots, readers):
        header = reader.__next__()
        endpos = header.index("ADD_TEXT")
        for row in reader:
            props = {k: v for k, v in zip(header[:endpos], row[:endpos])}
            # Ignore any row without id
            if utils.empty(props["id"]):
                continue
            props["type"] = root
            # Get additional text part from last columns
            xtra_text = []
            for title, text in zip(header[endpos+1:], row[endpos+1:]): 
                if utils.empty(text):
                    continue
                xtra_text.append("{{BLACK}}{}: {{GOLD}}{}".format(title, text))
            props["xtra_text"] = "\n".join(xtra_text)
            props["sort_pos"] = count

            db.add_consist(id_=props["id"], prop_map=props)
            count += 1
