#!/usr/bin/env ipython
import unittest
from unittest import TestCase
from dataclasses import dataclass


class TestIO(TestCase):
    pass

class TestRender(TestCase):
    pass

@dataclass
class Vertex:
    index: int = None


@dataclass
class VertexData:
    index: int = None
    val: int = None
    x: float = None
    y: float = None
    outIndex: int = None
    looseEdgesIndex: list[int] = None


@dataclass
class FaceData:
    index: int = None
    val: int = None
    sideIndex: int = None
    resolution: int = None
    tex: list[float] = None

@dataclass
class HalfEdgeData:
    index: int = None
    targIndex: int = None
    twinIndex: int = None
    prevIndex: int = None
    nextIndex: int = None
    polyIndex: int = None
    r: float = None
    g: float = None
    b: float = None
    tx: float = None
    ty: float = None

    def __repr__(self):
        return f"HE[{self.index}]"


def from_HEMESH(filename):
    """Read from HEMESH file"""
    indices: list[list[int]] = [[]]
    vertices: list[VertexData] = []
    faces: list[FaceData] = []
    edges: list[HalfEdgeData] = []
    with open(filename, 'r') as f:
        if (ft := f.readline().strip()) != 'HEMESH':
            raise ValueError(f"Unknown file type '{ft}'.")

        numVert, numFace, numEdge = [int(x) for x in f.readline().split(' ')]

        # Parse vertices
        while len(vertices) < numVert:
            if not (toks := f.readline().split(' ')):
                continue

            vert = VertexData()
            vert.index = int(toks[0])
            vert.val = int(toks[1])
            vert.x, vert.y = float(toks[2]), float(toks[3])
            vert.outIndex = int(toks[4])

            numOutEdges = int(toks[5])
            vert.looseEdgesIndex = [int(x) for x in toks[6:] if x.strip()]

            vertices.append(vert)

        # Faces
        while len(faces) < numFace:
            if not (toks := f.readline().split(' ')):
                continue

            face = FaceData()
            (face.index, face.val,
                face.sideIndex, face.res) = [int(x) for x in toks[:4]]
            face.tex = [float(x) for x in toks[4:]]

            faces.append(face)

        while len(edges) < numEdge:
            if not (toks := f.readline().split(' ')):
                continue

            edge = HalfEdgeData()

            edge.index = int(toks[0])
            edge.targIndex = int(toks[1])
            edge.twinIndex = int(toks[2])
            edge.prevIndex = int(toks[3])
            edge.nextIndex = int(toks[4])
            edge.polyIndex = int(toks[5])
            edge.r = float(toks[6])
            edge.g = float(toks[7])
            edge.b = float(toks[8])
            edge.tx = float(toks[9])
            edge.ty = float(toks[10])

            edges.append(edge)

        return (vertices, faces, edges)
