"""

3D-View angelehnt an die NASA Clipper GPS-Darstellung

"""

import os
import cairo
import math
from .page import Page

class XTETrack(Page):

    def __init__(self, pageno, cfg, appdata, boatdata):
        super().__init__(pageno, cfg, appdata, boatdata)
        self.xte = self.bd.getRef("XTE")
        self.cog = self.bd.getRef("COG")
        self.btw = self.bd.getRef("BTW")
        self.dtw = self.bd.getRef("DTW")
        self.wpname = "no data"
        self.symbol = cairo.ImageSurface.create_from_png(os.path.join(cfg['imgpath'], "ship.png"))

    def draw(self, ctx):
        # Beschriftung unter den Werten
        ctx.select_font_face("Ubuntu", cairo.FontSlant.NORMAL, cairo.FontWeight.BOLD)
        ctx.set_font_size(16) 
        ctx.move_to(50, 188);
        ctx.show_text("Cross-track error")
        ctx.move_to(270, 188)
        ctx.show_text("Track")
        ctx.move_to(45, 275);
        ctx.show_text("Distance to waypoint")
        ctx.move_to(260, 275);
        ctx.show_text("Bearing")
        ctx.stroke()

        # Meßwerte
        ctx.select_font_face("DSEG7 Classic")
        ctx.set_font_size(60)

        ctx.move_to(40, 170)
        #ctx.show_text(self.xte.format())
        ctx.show_text("2.3")
        ctx.move_to(220, 170)
        #ctx.show_text(self.cog.format())
        ctx.show_text("253")
        ctx.move_to(40, 257)
        #ctx.show_text(self.dtw.format())
        ctx.show_text("5.8")
        ctx.move_to(220, 257)
        #ctx.show_text(self.btw.format())
        ctx.show_text("248")

        # 3D-Ansicht oben
        # TODO Schiffssymbol
        ctx.save()
        ctx.set_source_surface(self.symbol, 186, 68)
        ctx.paint()
        ctx.restore()

        # Segmente: 2 1 0   3 4 5
        seg = [True] * 6
        points = {
            2: ((0, 54), (46, 24), (75, 24), (0, 90)),
            1: ((0, 100), (82, 24), (112, 24), (50, 100)),
            0: ((60, 100), (117, 24), (147, 24), (110, 100)),
            3: ((340, 100), (283, 24), (253, 24), (290, 100)),
            4: ((399, 100), (318, 24), (289, 24), (350, 100)),
            5: ((399, 54), (354, 24), (325, 24), (399, 90))
        }

        # Winkeldifferenz
        diff = (self.cog.value or 0) - (self.btw.value or 0)
        if diff < -180:
            diff += 360
        elif diff > 180:
            diff -= 360

        if diff > 0:
            order = (3, 4, 5, 0, 1, 2)
        else:
            order = (0, 1, 2, 3, 4, 5)

        # Anzahl aktiver Segmente
        seg_step = math.radians(3)
        nseg = min(abs(diff) / seg_step, 5)
        i = 0
        while nseg > 0:
            seg[order[i]] = False
            i += 1
            nseg -= 1

        # Segmente zeichnen
        for p in range(6):
            ctx.move_to(*points[p][0])
            ctx.line_to(*points[p][1])
            ctx.line_to(*points[p][2])
            ctx.line_to(*points[p][3])
            if seg[p]:
                ctx.fill()
            else:
                ctx.stroke()
