import cairo
import math
from .page import Page

class Rudder(Page):

    def __init__(self, pageno, cfg, appdata, boatdata):
        super().__init__(pageno, cfg, appdata, boatdata)
        self.buttonlabel[1] = 'MODE'
        self.mode = 'P'
        # Werte für Ruderausschlag
        self.valpri = self.bd.getRef("RPOS") # Primäres Ruder
        self.valsec = self.bd.getRef("PRPOS") # Sekundäres Ruder

    def handle_key(self, buttonid):
        if buttonid == 1:
            if self.mode == 'P':
                self.mode = 'S'
            else:
                self.mode = 'P'
            return True
        return False

    def draw(self, ctx):

        # Ruder auswählen
        if self.mode == 'P':
            valref = self.valpri
        else:
            valref = self.valsec

        # Rotationszentrum
        cx = 200
        cy = 150

        # Radius des Instruments
        r = 110

        # Titel
        ctx.select_font_face("Ubuntu", cairo.FontSlant.NORMAL, cairo.FontWeight.BOLD)
        ctx.set_font_size(32) 
        ctx.move_to(80, 70)
        ctx.show_text("Rudder Position")

        ctx.set_font_size(24)
        if valref.valid:
            ctx.move_to(175, 110)
            ctx.show_text(valref.unit)
        else:
            ctx.move_to(110, 110)
            ctx.show_text("no data available")
        ctx.stroke()

        # Debug 
        angle = 5

        # Rahmen
        ctx.set_source_rgb(*self.fgcolor)
        ctx.set_line_width(3)
        ctx.arc(cx, cy, r + 10, 0, math.pi)
        ctx.stroke()

        # Zentrum
        ctx.arc(cx, cy, 8, 0, 2*math.pi)
        ctx.fill()

        # Skala mit Strichen, Punkten und Beschriftung
        char = {
          90: "45",
          120: "30",
          150: "15",
          180: "0",
          210: "15",
          240: "30",
          270: "45"
        }
        # Zeichnen in 10°-Schritten
        ctx.set_font_size(16)
        for i in range(90, 271, 10):
            fx = math.sin(i / 180 * math.pi)
            fy = math.cos(i / 180 * math.pi)
            if i in char:
                x = cx + (r - 30) * fx
                y = cy - (r - 30) * fy
                self.draw_text_center(ctx, x, y, char[i])
                ctx.stroke()
            if i % 30 == 0:
                ctx.move_to(cx + (r - 10) * fx, cy - (r - 10) * fy)
                ctx.line_to(cx + (r + 10) * fx, cy - (r + 10) * fy)
                ctx.stroke()
            else:
                x = cx + r * fx
                y = cy - r * fy
                ctx.arc(x, y, 2, 0, 2*math.pi)
                ctx.fill()

        if valref.valid:
            p = ((cx - 6, cy), (cx + 6, cy), (cx + 2, cy + r - 50), (cx - 2, cy + r - 50))
            rudder = self.rotate((cx, cy), p, angle)
            ctx.move_to(*rudder[0])
            for point in rudder[1:]:
                ctx.line_to(*point)
            ctx.fill()
