#!/usr/bin/env python2
#
# by
# Robin Wittler <real@the-real.org> (speedometer mode)
# and
# Chen Wei <weichen302@gmx.com> (nautical mode)
#
# BSD terms apply: see the file COPYING in the distribution root for details.

import pygtk
pygtk.require('2.0')
import gtk
import cairo
import gobject
import gps
from math import pi
from math import cos
from math import sin
from math import sqrt
from math import radians
from socket import error as SocketError


class Speedometer(gtk.DrawingArea):
    def __init__(self, speed_unit=None):
        gtk.DrawingArea.__init__(self)
        self.MPH_UNIT_LABEL = 'mph'
        self.KPH_UNIT_LABEL = 'kmh'
        self.KNOTS_UNIT_LABEL = 'knots'
        self.conversions = {
            self.MPH_UNIT_LABEL: gps.MPS_TO_MPH,
            self.KPH_UNIT_LABEL: gps.MPS_TO_KPH,
            self.KNOTS_UNIT_LABEL: gps.MPS_TO_KNOTS
        }
        self.speed_unit = speed_unit or self.MPH_UNIT_LABEL
        if self.speed_unit not in self.conversions:
            raise TypeError(
                '%s is not a valid speed unit'
                % (repr(speed_unit))
            )


class LandSpeedometer(Speedometer):
    def __init__(self, speed_unit=None):
        Speedometer.__init__(self, speed_unit)
        self.connect('expose_event', self.expose_event)
        self.long_ticks = (2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8)
        self.short_ticks = (0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9)
        self.long_inset = lambda x: 0.1 * x
        self.middle_inset = lambda x: self.long_inset(x) / 1.5
        self.short_inset = lambda x: self.long_inset(x) / 3
        self.res_div = 10.0
        self.res_div_mul = 1
        self.last_speed = 0
        self.nums = {
            -8: 0,
            -7: 10,
            -6: 20,
            -5: 30,
            -4: 40,
            -3: 50,
            -2: 60,
            -1: 70,
            0: 80,
            1: 90,
            2: 100
        }

    def expose_event(self, _unused, event, _empty=None):
        self.cr = self.window.cairo_create()
        self.cr.rectangle(
            event.area.x,
            event.area.y,
            event.area.width,
            event.area.height
        )
        self.cr.clip()
        x, y = self.get_x_y()
        width, height = self.window.get_size()
        radius = self.get_radius(width, height)
        self.cr.set_line_width(radius / 100)
        self.draw_arc_and_ticks(width, height, radius, x, y)
        self.draw_needle(self.last_speed, radius, x, y)
        self.draw_speed_text(self.last_speed, radius, x, y)

    def draw_arc_and_ticks(self, width, height, radius, x, y):
        self.cr.set_source_rgb(1.0, 1.0, 1.0)
        self.cr.rectangle(0, 0, width, height)
        self.cr.fill()
        self.cr.set_source_rgb(0.0, 0.0, 0.0)

        # draw the speedometer arc
        self.cr.arc_negative(x, y, radius, radians(60), radians(120))
        self.cr.stroke()
        long_inset = self.long_inset(radius)
        middle_inset = self.middle_inset(radius)
        short_inset = self.short_inset(radius)

        # draw the ticks
        for i in self.long_ticks:
            self.cr.move_to(
                x + (radius - long_inset) * cos(i * pi / 6.0),
                y + (radius - long_inset) * sin(i * pi / 6.0)
            )
            self.cr.line_to(
                x + (radius + (self.cr.get_line_width() / 2)) * cos(i * pi / 6.0),
                y + (radius + (self.cr.get_line_width() / 2)) * sin(i * pi / 6.0)
            )
            self.cr.select_font_face(
                'Georgia',
                cairo.FONT_SLANT_NORMAL,
            )
            self.cr.set_font_size(radius / 10)
            self.cr.save()
            _num = str(self.nums.get(i) * self.res_div_mul)
            (
                _x_bearing,
                _y_bearing,
                t_width,
                t_height,
                _x_advance,
                _y_advance
            ) = self.cr.text_extents(_num)

            if i in (-8, -7, -6, -5, -4):
                self.cr.move_to(
                    (x + (radius - long_inset - (t_width / 2)) * cos(i * pi / 6.0)),
                    (y + (radius - long_inset - (t_height * 2)) * sin(i * pi / 6.0))
                )
            elif i in (-2, -1, 0, 2, 1):
                self.cr.move_to(
                    (x + (radius - long_inset - (t_width * 1.5)) * cos(i * pi / 6.0)),
                    (y + (radius - long_inset - (t_height * 2)) * sin(i * pi / 6.0))
                )
            elif i in (-3,):
                self.cr.move_to(
                    (x - t_width / 2),
                    (y - radius + self.long_inset(radius) * 2 + t_height)
                )
            self.cr.show_text(_num)
            self.cr.restore()

            if i != self.long_ticks[0]:
                self.cr.move_to(
                    x + (radius - middle_inset) * cos((i + 0.5) * pi / 6.0),
                    y + (radius - middle_inset) * sin((i + 0.5) * pi / 6.0)
                )
                self.cr.line_to(
                    x + (radius + (self.cr.get_line_width() / 2)) *
                    cos((i + 0.5) * pi / 6.0),
                    y + (radius + (self.cr.get_line_width() / 2)) *
                    sin((i + 0.5) * pi / 6.0)
                )

            for z in self.short_ticks:
                if i < 0:
                    self.cr.move_to(
                        x + (radius - short_inset) * cos((i + z) * pi / 6.0),
                        y + (radius - short_inset) * sin((i + z) * pi / 6.0)
                    )
                    self.cr.line_to(
                        x + (radius + (self.cr.get_line_width() / 2)) * cos((i + z) * pi / 6.0),
                        y + (radius + (self.cr.get_line_width() / 2)) * sin((i + z) * pi / 6.0)
                    )
                else:
                    self.cr.move_to(
                        x + (radius - short_inset) * cos((i - z) * pi / 6.0),
                        y + (radius - short_inset) * sin((i - z) * pi / 6.0)
                    )
                    self.cr.line_to(
                        x + (radius + (self.cr.get_line_width() / 2)) * cos((i - z) * pi / 6.0),
                        y + (radius + (self.cr.get_line_width() / 2)) * sin((i - z) * pi / 6.0)
                    )
            self.cr.stroke()

    def draw_needle(self, speed, radius, x, y):
        self.cr.save()
        inset = self.long_inset(radius)
        speed = speed * self.conversions.get(self.speed_unit)
        speed = speed / (self.res_div * self.res_div_mul)
        actual = self.long_ticks[-1] + speed
        if actual > self.long_ticks[0]:
            self.res_div_mul += 1
            speed = speed / (self.res_div * self.res_div_mul)
            actual = self.long_ticks[-1] + speed
        self.cr.move_to(x, y)
        self.cr.line_to(
            x + (radius - (2 * inset)) * cos(actual * pi / 6.0),
            y + (radius - (2 * inset)) * sin(actual * pi / 6.0)
        )
        self.cr.stroke()
        self.cr.restore()

    def draw_speed_text(self, speed, radius, x, y):
        self.cr.save()
        speed = '%.2f %s' % (
                speed * self.conversions.get(self.speed_unit),
                self.speed_unit
        )
        self.cr.select_font_face(
            'Georgia',
            cairo.FONT_SLANT_NORMAL,
            # cairo.FONT_WEIGHT_BOLD
        )
        self.cr.set_font_size(radius / 10)
        _x_bearing, _y_bearing, t_width, _t_height = self.cr.text_extents(speed)[:4]
        self.cr.move_to((x - t_width / 2), (y + radius) - self.long_inset(radius))
        self.cr.show_text(speed)
        self.cr.restore()

    def get_x_y(self):
        rect = self.get_allocation()
        x = (rect.x + rect.width / 2.0)
        y = (rect.y + rect.height / 2.0) - 20
        return x, y

    def get_radius(self, width, height):
        return min(width / 2.0, height / 2.0) - 20


class NauticalSpeedometer(Speedometer):
    HEADING_SAT_GAP = 0.8
    SAT_SIZE = 10  # radius of the satellite circle in skyview

    def __init__(self, speed_unit=None, maxspeed=100):
        Speedometer.__init__(self, speed_unit)
        self.connect('expose_event', self.expose_event)
        self.long_inset = lambda x: 0.05 * x
        self.mid_inset = lambda x: self.long_inset(x) / 1.5
        self.short_inset = lambda x: self.long_inset(x) / 3
        self.last_speed = 0
        self.satellites = []
        self.last_heading = 0
        self.maxspeed = int(maxspeed)

    @staticmethod
    def polar2xy(radius, angle, polex, poley):
        '''convert Polar coordinate to Cartesian coordinate system
        the y axis in pygtk points downward
        Args:
           radius:
           angle: azimuth from from Polar coordinate system, in radian
           polex and poley are the Cartesian coordinate of the pole
        return a tuple contains (x, y)'''
        return (polex + cos(angle) * radius, poley - sin(angle) * radius)

    def expose_event(self, _unused, event, _empty=None):
        self.cr = self.window.cairo_create()
        self.cr.rectangle(
            event.area.x,
            event.area.y,
            event.area.width,
            event.area.height
        )
        self.cr.clip()
        x, y = self.get_x_y()
        width, height = self.window.get_size()
        radius = self.get_radius(width, height)
        self.cr.set_line_width(radius / 100)
        self.draw_arc_and_ticks(width, height, radius, x, y)
        self.draw_heading(20, self.last_heading, radius, x, y)
        for sat in self.satellites:
            self.draw_sat(sat, radius * NauticalSpeedometer.HEADING_SAT_GAP, x, y)
        self.draw_speed(radius, x, y)

    def draw_text(self, x, y, text, fontsize=10):
        '''draw text at given location
        Args:
            x, y is the center of textbox'''
        txt = str(text)
        self.cr.new_sub_path()
        self.cr.set_source_rgba(0, 0, 0)
        self.cr.select_font_face('Sans',
                                 cairo.FONT_SLANT_NORMAL,
                                 cairo.FONT_WEIGHT_BOLD)
        self.cr.set_font_size(fontsize)
        (_x_bearing, _y_bearing,
         t_width, t_height) = self.cr.text_extents(txt)[:4]
        # set the center of textbox
        self.cr.move_to(x - t_width / 2, y + t_height / 2)
        self.cr.show_text(txt)

    def draw_arc_and_ticks(self, width, height, radius, x, y):
        '''Draw a serial of circle, with ticks in outmost circle'''

        self.cr.set_source_rgb(1.0, 1.0, 1.0)
        self.cr.rectangle(0, 0, width, height)
        self.cr.fill()
        self.cr.set_source_rgba(0, 0, 0)

        # draw the speedmeter arc
        rspeed = radius + 50
        self.cr.arc(x, y, rspeed, 2 * pi / 3, 7 * pi / 3)
        self.cr.set_source_rgba(0, 0, 0, 1.0)
        self.cr.stroke()
        s_long = self.long_inset(rspeed)
        s_middle = self.mid_inset(radius)
        s_short = self.short_inset(radius)
        for i in xrange(11):
            # draw the large ticks
            alpha = (8 - i) * pi / 6
            self.cr.move_to(*NauticalSpeedometer.polar2xy(rspeed, alpha, x, y))
            self.cr.set_line_width(radius / 100)
            self.cr.line_to(*NauticalSpeedometer.polar2xy(rspeed - s_long, alpha, x, y))
            self.cr.stroke()
            self.cr.set_line_width(radius / 200)
            xf, yf = NauticalSpeedometer.polar2xy(rspeed + 10, alpha, x, y)
            stxt = (self.maxspeed / 10) * i
            self.draw_text(xf, yf, stxt, fontsize=radius / 15)

        for i in xrange(1, 11):
            # middle tick
            alpha = (8 - i) * pi / 6
            beta = (17 - 2 * i) * pi / 12
            self.cr.move_to(*NauticalSpeedometer.polar2xy(rspeed, beta, x, y))
            self.cr.line_to(*NauticalSpeedometer.polar2xy(rspeed - s_middle, beta, x, y))

            #  short tick
            for n in xrange(10):
                gamma = alpha + n * pi / 60
                self.cr.move_to(*NauticalSpeedometer.polar2xy(rspeed, gamma, x, y))
                self.cr.line_to(*NauticalSpeedometer.polar2xy(rspeed - s_short, gamma, x, y))

        # draw the heading arc
        self.cr.new_sub_path()
        self.cr.arc(x, y, radius, 0, 2 * pi)
        self.cr.stroke()
        self.cr.arc(x, y, radius - 20, 0, 2 * pi)
        self.cr.set_source_rgba(0, 0, 0, 0.20)
        self.cr.fill()
        self.cr.set_source_rgba(0, 0, 0)

        # heading label 90/180/270
        for n in xrange(0, 4):
            label = str(n * 90)
            # self.cr.set_source_rgba(0, 1, 0)
            # radius * (1 + NauticalSpeedometer.HEADING_SAT_GAP),
            tbox_x, tbox_y = NauticalSpeedometer.polar2xy(
                radius * 0.88,
                (1 - n) * pi / 2,
                x, y)
            self.draw_text(tbox_x, tbox_y,
                           label, fontsize=radius / 20)

        # draw the satellite arcs
        skyradius = radius * NauticalSpeedometer.HEADING_SAT_GAP
        self.cr.set_line_width(radius / 200)
        self.cr.set_source_rgba(0, 0, 0)
        self.cr.arc(x, y, skyradius, 0, 2 * pi)
        self.cr.set_source_rgba(1, 1, 1)
        self.cr.fill()
        self.cr.set_source_rgba(0, 0, 0)

        self.cr.arc(x, y, skyradius * 2 / 3, 0, 2 * pi)
        self.cr.arc(x, y, skyradius / 3, 0, 2 * pi)

        # draw the cross hair
        self.cr.move_to(x - skyradius, y)
        self.cr.line_to(x + skyradius, y)
        self.cr.move_to(x, y - skyradius)
        self.cr.line_to(x, y + skyradius)
        self.cr.set_line_width(radius / 200)
        self.cr.stroke()

        long_inset = self.long_inset(radius)
        mid_inset = self.mid_inset(radius)
        short_inset = self.short_inset(radius)

        # draw the large ticks
        for i in xrange(12):
            agllong = i * pi / 6
            self.cr.move_to(*NauticalSpeedometer.polar2xy(radius - long_inset, agllong, x, y))
            self.cr.line_to(*NauticalSpeedometer.polar2xy(radius, agllong, x, y))
            self.cr.set_line_width(radius / 100)
            self.cr.stroke()
            self.cr.set_line_width(radius / 200)

            # middle tick
            aglmid = (i + 0.5) * pi / 6
            self.cr.move_to(*NauticalSpeedometer.polar2xy(radius - mid_inset, aglmid, x, y))
            self.cr.line_to(*NauticalSpeedometer.polar2xy(radius, aglmid, x, y))

            #  short tick
            for n in xrange(1, 10):
                aglshrt = agllong + n * pi / 60
                self.cr.move_to(*NauticalSpeedometer.polar2xy(radius - short_inset, aglshrt, x, y))
                self.cr.line_to(*NauticalSpeedometer.polar2xy(radius, aglshrt, x, y))
            self.cr.stroke()

    def draw_heading(self, trig_height, heading, radius, x, y):
        hypo = trig_height * 2 / sqrt(3)
        h = pi / 2 - radians(heading)  # to xyz
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          