#!/usr/bin/env python

import sys
import gtk
import re
import os
import dbus
import ParrotZik
import BluetoothPairedDevices
from SysIndicator import *
from dbus.mainloop.glib import DBusGMainLoop
import gobject

UPDATE_FREQUENCY = 30  # seconds
BLUEZ_VERSION = 5


class ParrotZikIndicator(SysIndicator):
    def __init__(self):

        self.batteryState = "In Use"
        self.batteryLevel = "Unknown"
        self.menu = UniversalMenu()

        self.info_item = MenuItem("Parrot Zik Not connected..", None, sensitive=False)
        self.menu.append(self.info_item)

        self.battery_level = MenuItem("Battery Level:", None, sensitive=False)
        self.menu.append(self.battery_level)

        self.battery_state = MenuItem("Battery State:", None, sensitive=False)
        self.menu.append(self.battery_state)

        self.firmware_version = MenuItem("Firmware Version:", None, sensitive=False)
        self.menu.append(self.firmware_version)

        self.check = MenuItem("Noise Cancellation", self.toggleANC, sensitive=False, checkitem=True)
        self.menu.append(self.check)

        self.check2 = MenuItem("Auto Connection", self.toggleAuto, sensitive=False, checkitem=True)
        self.menu.append(self.check2)

        self.check3 = MenuItem("Lou Reed Mode", self.toggleLouReedMode, sensitive=False, checkitem=True)
        self.menu.append(self.check3)

        self.check4 = MenuItem("Concert Hall Mode", self.toggleParrotConcertHall, sensitive=False, checkitem=True)
        self.menu.append(self.check4)

        self.quit = MenuItem("Quit", sys.exit, sensitive=True, checkitem=True)
        self.menu.append(self.quit)

        SysIndicator.__init__(self, icon="zik-audio-headset", menu=self.menu)

        self.connected = False
        self.p = re.compile('90:03:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}')

    def EstablishConnection(self):
        if self.connected:
            if not self.parrot.sock:
                print "Lost connection"
                self.connected = False
            else:
                print "Connection already established"
        else:
            mac = BluetoothPairedDevices.parrot_zik_mac()
            if mac:
                self.parrot = ParrotZik.ParrotZik(mac)
                if not self.parrot.sock:
                    print "Failed to connect to Parrot Zik %s" % mac
                    return False

                self.connected = True
                self.name = self.parrot.get_friendly_name()
                self.version = self.parrot.get_version()

                self.check.set_sensitive(True)
                self.check2.set_sensitive(True)
                self.check3.set_sensitive(True)
                self.check4.set_sensitive(True)

                if self.parrot.get_noise_cancel() == "true":
                    self.check.set_active(True)
                else:
                    self.check.set_active(False)

                if self.parrot.get_auto_connection() == "true":
                    self.check2.set_active(True)
                else:
                    self.check2.set_active(False)

                if self.parrot.get_lou_reed_mode() == "true":
                    self.check3.set_active(True)
                else:
                    self.check3.set_active(False)

                if self.parrot.get_parrot_concert_hall() == "true":
                    self.check4.set_active(True)
                else:
                    self.check4.set_active(False)

                self.CheckBattery()
        return True

    def toggleANC(self, widget):
        if self.connected:
            if self.check.get_active():
                self.parrot.set_noise_cancel("true")
            else:
                self.parrot.set_noise_cancel("false")

    def toggleAuto(self, widget):
        if self.connected:
            if self.check2.get_active():
                self.parrot.set_auto_connection("true")
            else:
                self.parrot.set_auto_connection("false")

    def toggleLouReedMode(self, widget):
        if self.connected:
            if self.check3.get_active():
                self.parrot.set_lou_reed_mode("true")
                self.check4.set_sensitive(False)
            else:
                self.parrot.set_lou_reed_mode("false")
                self.check4.set_sensitive(True)

    def toggleParrotConcertHall(self, widget):
        if self.connected:
            if self.check4.get_active():
                self.parrot.set_parrot_concert_hall("true")
            else:
                self.parrot.set_parrot_concert_hall("false")

    def CheckBattery(self):
        if self.connected:
            print "Updating battery"
            self.batteryLevel = int(self.parrot.get_battery_level())

            if self.parrot.BatteryCharging:
                self.batteryLevel = "Charging"
                self.set_icon("zik-battery-charging")
                self.batteryState = "Charging"
            elif self.batteryLevel > 80:
                self.set_icon("zik-battery-100")
                self.batteryState = "In Use"
            elif self.batteryLevel > 60:
                self.set_icon("zik-battery-080")
                self.batteryState = "In Use"
            elif self.batteryLevel > 40:
                self.set_icon("zik-battery-060")
                self.batteryState = "In Use"
            elif self.batteryLevel > 20:
                self.set_icon("zik-battery-040")
                self.batteryState = "In Use"
            else:
                self.set_icon("zik-battery-low")

            self.info_item.set_label("Connected to: " + self.name)
            self.firmware_version.set_label("Firmware version: " + self.version)
            self.battery_state.set_label("State: " + self.batteryState)
            self.battery_level.set_label("Battery Level: " + str(self.batteryLevel))
        else:
            self.set_icon("zik-audio-headset")
            self.info_item.set_label("Parrot Zik Not connected..")
            self.check.set_sensitive(False)
            self.check2.set_sensitive(False)
            self.check3.set_sensitive(False)
            self.check4.set_sensitive(False)
        return True

    def main(self):
        SysIndicator.main(self)


if __name__ == "__main__":

    indicator = ParrotZikIndicator()
    parrot_zik_id = '90:03:B7:5F:5F:82'
    dbus_loop = DBusGMainLoop()
    bus = dbus.SystemBus(mainloop=dbus_loop)

    if BLUEZ_VERSION >= 5:

        manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
        objects = manager.GetManagedObjects()

        for path, obj in objects.items():
            if "org.bluez.Device1" in obj:
                device = obj["org.bluez.Device1"]
                if device["Name"] and device["Address"] == parrot_zik_id:
                    print device
                    if device["Connected"]:
                        indicator.EstablishConnection()
                    print "Headset path: " + path
                    headset = bus.get_object('org.bluez', path)
                    #headset_interface = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Adapter")

    else:

        manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.bluez.Manager")
        headset_path = manager.DefaultAdapter() + '/dev_' + parrot_zik_id.replace(":", "_")
        headset = dbus.Interface(bus.get_object("org.bluez", headset_path), "org.bluez.Adapter")


    def handler():
        print "Handler called"
        indicator.EstablishConnection()
    headset.
    print headset.bus_name
    print headset.proxy_object
    headset.connect_to_signal("Connected", handler)
    headset.connect_to_signal("Disconnected", handler)

    mainloop = gobject.MainLoop()

    try:
        mainloop.run()
    except KeyboardInterrupt:
        mainloop.quit()
        exit()
    indicator.main()
