import io

import lxml.etree

from cad_parser.errors import CadParserError

NONE_VALUE_STRINGS = ['', 'None', 'Keine', '-']

def consolidate_colors(teeth):
    colors = list(set([t.color for t in teeth if t.color]))

    if len(colors) == 0:
        return None

    if len(colors) > 1:
        return 'Mixed'

    return colors[0]

def get_text(node, xml_path: str, ignore_nullable: bool=True):
    target = node.find(xml_path)
    if target == None: return
    if ignore_nullable and (target.text in NONE_VALUE_STRINGS): return
    return target.text

def parse_document(source: str | io.IOBase):
    if isinstance(source, str):
        return lxml.etree.fromstring(source)
    elif isinstance(source, io.IOBase):
        return lxml.etree.parse(source)
    else:
        raise NotImplementedError(f'{source} is neither str nor a file-like object')

def unn_to_fdi(number: int) -> int:
    if number >= 1 and number <= 8:
        return 19 - number
    if number >= 9 and number <= 16:
        return 12 + number
    if number >= 17 and number <= 24:
        return 55 - number
    if number >= 25 and number <= 32:
        return 16 + number

    raise CadParserError(f'Invalid tooth indication number {number}')
