# module
# load cables from JSON ['connectors]

import json
import pandas as pd
import regex as re

# load cable references from JSON and return them as a list and list of duplicated cables (if any)
def loadjson_data(filename):
    with open(filename, mode='r') as filejson:
	    datajson = json.loads(filejson.read())
    cbl = pd.Series(list(datajson['connectors'].keys()),dtype=str)
    cb_dup = cbl[cbl.duplicated()]  # TODO: in realtà non funziona perché il comando json.loads interpreta il dato "connectors" come un dizionario (giustamente) e quindi non considera i duplicati
    if len(cb_dup) == 0:
        return cbl.tolist(), None
    else:
        return cbl.tolist(), cb_dup.tolist()


# load cable references from SVG and return them as a list
def loadsvg_data(filename):
    pattern = r'"([^"]*)"'  # select all text between double quotes "  "
    listcablecodes = []
    with open(filename, mode='r') as svgfile:
        for line in svgfile:
            if "<g id=" in line:
                m = re.search(pattern, line)
                if m:
                    cablecode = m.group(0)[1:-1]
                    if "illustration" not in cablecode:
                        listcablecodes.append(cablecode)            
    return listcablecodes