from core.common import *
from data.type import Point


def load_data(filename: str):
    filename = 'file/' + filename
    origin = Point(0, 0)
    coordinate = ''
    part_skiprows, part_rows, step_skiprows, step_rows = -1, -1, -1, -1

    line_counter = 0
    with open(filename, 'r') as file:
        while line := file.readline():
            if line == '[PART]\n':
                part_skiprows = line_counter + 1
            elif line == '[STEP]\n':
                step_skiprows = line_counter + 1
            elif line == '\n':
                if part_skiprows != -1 and part_rows == -1:
                    part_rows = line_counter - part_skiprows
                elif step_skiprows != -1 and step_rows == -1:
                    step_rows = line_counter - step_skiprows

            if line.startswith('Coordinate'):
                coordinate = line.split('=')[1].strip()
            elif line.startswith('Placement Origin'):
                x, y = line.split('=')[1].strip().split(',')
                origin.x, origin.y = float(x.strip()), float(y.strip())

            line_counter += 1

    if part_skiprows != -1 and part_rows == -1:
        part_rows = line_counter - part_skiprows
    if step_skiprows != -1 and step_rows == -1:
        step_rows = line_counter - step_skiprows

    step_data = pd.DataFrame(
        pd.read_csv(filepath_or_buffer=filename, skiprows=step_skiprows, nrows=step_rows, sep='\t', header=None))
    step_data.columns = ["ref", "x", "y", "z", "r", "part", "layer"]

    part_col = ["part", "fdr", "nz", "fdn"]
    try:
        if part_skiprows != -1:
            part_data = pd.DataFrame(pd.read_csv(filepath_or_buffer=filename, sep='\t', header=None,
                                                 skiprows=part_skiprows, nrows=part_rows))
            part_data.columns = part_col
        else:
            part_data = pd.DataFrame(columns=part_col)
    except:
        part_data = pd.DataFrame(columns=part_col)


    for _, data in step_data.iterrows():
        if data.part not in part_data.part.values:
            raise Exception("unregistered component:  " + data.part)

    if coordinate == "UPPER RIGHT" or coordinate == "LOWER RIGHT":
        step_data['x'] = -step_data['x']
    if coordinate == "UPPER LEFT" or coordinate == "UPPER RIGHT":
        step_data['y'] = -step_data['y']

    step_data['x'] += origin.x
    step_data['y'] += origin.y

    return part_data, step_data


def load_config(filepath: str):
    pass

