#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gtk, Gdk, GObject, Pango
from threading import Thread
import cairo
import time
import signal
import os
import clocktools as clt


"""
Budgie ShowTime
Author: Jacob Vlijm
Copyright=Copyright © 2017-2018 Ubuntu Budgie Developers
Website=https://ubuntubudgie.org
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
should have received a copy of the GNU General Public License along with this
program.  If not, see <http://www.gnu.org/licenses/>.
"""

time_color = clt.hexcolor(clt.read_color(clt.timecolor))
date_color = clt.hexcolor(clt.read_color(clt.datecolor))
posfile = os.path.join(clt.prefspath, "position")
font = clt.get_font()


class ShowTimeWin(Gtk.Window):
    def __init__(self):

        Gtk.Window.__init__(self, title="PrVflash")

        # window props, bindings
        self.set_keep_below(True)
        self.set_wmclass("Showtime", "showtime")
        self.set_type_hint(Gdk.WindowTypeHint.DESKTOP)
        self.set_decorated(False)
        self.connect("destroy", Gtk.main_quit)
        self.set_skip_taskbar_hint(True)
        # transparency
        screen = self.get_screen()
        visual = screen.get_rgba_visual()
        if all([visual, screen.is_composited()]):
            self.set_visual(visual)
        self.set_app_paintable(True)
        self.connect("draw", self.area_draw)
        # main grid
        self.timegrid = Gtk.Grid()
        self.timelabel = Gtk.Label("")
        self.datelabel = Gtk.Label("")

        self.timelabel.modify_font(Pango.FontDescription(font + " 60"))
        self.timelabel.modify_fg(Gtk.StateFlags.NORMAL,
                                 Gdk.color_parse(time_color))
        self.timelabel.set_xalign(1)

        self.datelabel.modify_font(Pango.FontDescription(font + " 25"))
        self.datelabel.modify_fg(Gtk.StateFlags.NORMAL,
                                 Gdk.color_parse(date_color))
        self.datelabel.set_xalign(1)
        self.timegrid.attach(self.timelabel, 0, 0, 1, 1)
        self.timegrid.attach(self.datelabel, 0, 1, 1, 1)
        self.add(self.timegrid)
        # create rows
        self.set_textposition()
        self.show_all()
        self.update = Thread(target=self.show_time)
        # daemonize the thread to make the indicator stopable
        self.update.setDaemon(True)
        self.update.start()

    def set_textposition(self):
        pos = clt.get_textposition()
        self.move(pos[1], pos[2])

    def check_12hrs(self, timedate):
        if twelvehrs:
            time = timedate[0].split(":")
            hrs = int(time[0])
            add = " PM" if 12 <= hrs < 24 else " AM"
            hrs = hrs - 12 if hrs > 12 else hrs
            hrs = hrs + 12 if hrs < 1 else hrs
            newtime = ":".join([str(hrs), time[1]]) + add
            timedate[0] = newtime
        return timedate

    def fix_leadingzeros(self, currtime):
        tofix = currtime[1].split()
        currtime[1] = " ".join([it.lstrip("0") for it in tofix])
        return currtime

    def show_time(self):
        wait = 1
        while True:
            time.sleep(wait)
            wait = 61 - int(time.time()) % 60
            currtime = time.strftime('%H:%M-%d %B %Y')
            timedate = self.fix_leadingzeros(currtime.split("-"))
            if not mutetime:
                timedate = self.check_12hrs(timedate)
                GObject.idle_add(
                    self.timelabel.set_text,
                    timedate[0],
                    priority=GObject.PRIORITY_DEFAULT
                )
            if not mutedate:
                GObject.idle_add(
                    self.datelabel.set_text,
                    timedate[1],
                    priority=GObject.PRIORITY_DEFAULT
                )

    def stop(self, *args):
        Gtk.main_quit()

    def area_draw(self, widget, cr):
        # set transparent color
        cr.set_source_rgba(0.2, 0.2, 0.2, 0)
        cr.set_operator(cairo.OPERATOR_SOURCE)
        cr.paint()
        cr.set_operator(cairo.OPERATOR_OVER)


def show():
    ShowTimeWin()
    GObject.threads_init()
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    Gtk.main()


mutetime = os.path.exists(clt.mute_time)
mutedate = os.path.exists(clt.mute_date)
twelvehrs = os.path.exists(clt.twelve_hrs)


# only run clock if it should actually show something
if not all([mutetime, mutedate]):
    show()
