import enum

from gui_qt.Qt import QtGui, QtCore


sym_list = ['o', 's', 'd', 't1', 't3', 't', 't2', '+', 'x', 'star']


def symbolcycle():
    while True:
        for s in SymbolStyle:
            if s == SymbolStyle.No:
                continue
            yield s


class SymbolStyle(enum.Enum):
    No = 0
    Circle = 1
    Square = 2
    Diamond = 3
    TriangleUp = 4
    TriangleLeft = 5
    TriangleDown = 6
    TriangleRight = 7
    Plus = 8
    X = 9
    Star = 10

    def to_str(self):
        if self.value == 0:
            return None
        else:
            return sym_list[self.value-1]

    @staticmethod
    def from_str(value):
        try:
            return SymbolStyle(sym_list.index(value) + 1)
        except ValueError:
            return SymbolStyle.No


def symbol_path(style: SymbolStyle, size: QtCore.QRectF) -> QtGui.QPainterPath:
    paths = {3: [(0.1, 0.5), (0.5, 0), (0.9, 0.5), (0.5, 1)],
             4: [(0, 1), (0.5, 0), (1, 1)],
             5: [(1, 1), (1, 0), (0, 0.5)],
             6: [(0, 0), (0.5, 1), (1, 0)],
             7: [(0, 1), (0, 0), (1, 0.5)],
             8: [(0, 0.5), (1, 0.5), (0.5, 0.5), (0.5, 0), (0.5, 1), (0.5, 0.5)],
             9: [(0.1, 0.1), (0.9, 0.9), (0.5, 0.5), (0.1, 0.9), (0.9, 0.1), (0.5, 0.5)],
             10: [(0.1, 0.1), (0.9, 0.9), (0.5, 0.5), (0.1, 0.9), (0.9, 0.1), (0.5, 0.5),
                  (0, 0.5), (1, 0.5), (0.5, 0.5), (0.5, 0), (0.5, 1), (0.5, 0.5)]
             }

    p = QtGui.QPainterPath()
    if style == SymbolStyle.No:
        pass

    elif style == SymbolStyle.Circle:
        p.addEllipse(size)

    elif style == SymbolStyle.Square:
        p.addRect(size)

    else:
        width = size.width()
        height = size.height()
        pts = paths[style.value]
        p.moveTo(pts[0][0]*width, pts[0][1]*height)
        for (x, y) in pts[1:]:
            p.lineTo(x*width, y*height)
        p.closeSubpath()

    return p


def make_symbol_pixmap(style):
    px = QtGui.QPixmap(14, 14)
    px.fill(QtCore.Qt.transparent)
    px_size = px.rect().adjusted(1, 1, -1, -1)

    painter = QtGui.QPainter(px)
    painter.setRenderHint(QtGui.QPainter.Antialiasing)

    pal = QtGui.QGuiApplication.palette()
    col = pal.color(QtGui.QPalette.Text)

    painter.setPen(QtGui.QPen(col, 1, QtCore.Qt.SolidLine, QtCore.Qt.SquareCap, QtCore.Qt.MiterJoin))
    painter.setBrush(col)
    painter.drawPath(symbol_path(style, QtCore.QRectF(px_size)))

    painter.end()

    return px
