#!/usr/bin/env python3
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango
import sys
import wmovertools as wmt
import os

"""
Budgie WindowMover
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/>.
"""

button_hsize = 80
button_vsize = 50
fpath = wmt.fpath
font = wmt.get_font()

css_data = """
.moverwindow {
    background-color: #353945;
}
.moverbutton {
    background-color: #353945;
    color: #C8C8C8;
    border-width: 0px;
    border-color: #858C96;
    padding: 1px;
    border-radius: 0px;
}
.moverbutton:hover {
    background-color: shade (@bg_color, 0.4);
    color: shade (@color, 0.2)
}
"""

try:
    os.remove(fpath)
except FileNotFoundError:
    pass


class Splash(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="w_moversplash")
        provider = Gtk.CssProvider.new()
        provider.load_from_data(css_data.encode())
        self.set_skip_taskbar_hint(True)
        maingrid = Gtk.Grid()
        self.add(maingrid)
        maingrid.set_border_width(0)
        wsdata = wmt.get_wsdata()
        self.n_spaces = wsdata[0]
        currspace = wsdata[1]
        # create button- row
        if subj == "none":
            l_char = "◂ "
            r_char = " ▸"
        else:
            l_char = "•"
            r_char = "•"
        for n in range(self.n_spaces):
            label = l_char + str(n + 1) + r_char if n == currspace else n + 1
            button = Gtk.Button(label)
            st_cont = button.get_style_context()
            st_cont.add_class("moverbutton")
            button.set_size_request(button_hsize, button_vsize)
            maingrid.attach(button, n, 0, 1, 1)
            button.modify_font(Pango.FontDescription(font + " 15"))
            if subj != "none":
                button.connect("clicked", self.move_to, subj, n)
            else:
                button.connect("clicked", self.move_desktop, subj, n)
            button.connect("enter-notify-event", self.busy)
        self.connect('key-press-event', self.get_key)
        x_size = self.n_spaces * button_hsize
        self.move((x_res / 2 - x_size / 2) + xoffset, y_res - 180 + yoffset)

    def move_to(self, button, subj, wspace):
        wmt.run(["/usr/bin/wmctrl", "-ir", subj.strip(), "-t", str(wspace)])
        targetx = str(100 + xoffset)
        targety = str(100 + yoffset)
        wmt.run(["/usr/bin/xdotool", "windowmove", subj, targetx, targety])
        self.stop()

    def busy(self, *args):
        open(fpath, "wt").write("")

    def move_desktop(self, button, subj, wspace):
        wmt.run(["/usr/bin/wmctrl", "-s", str(wspace)])
        self.stop()

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

    def get_key(self, val1, val2):
        keypressed = Gdk.keyval_name(val2.keyval)
        try:
            wspace = int(keypressed) - 1
        except ValueError:
            if keypressed in ["Left", "Right"]:
                self.busy()
        else:
            if wspace not in range(self.n_spaces):
                pass
            else:
                self.move_to(
                    None, subj, wspace
                ) if subj != "none" else self.move_desktop(
                    None, None, wspace
                )


def run_moverbar():
    # get the style from the css file and apply it
    cssProvider = Gtk.CssProvider.new()
    cssProvider.load_from_data(css_data.encode())
    screen = Gdk.Screen.get_default()
    styleContext = Gtk.StyleContext()
    styleContext.add_provider_for_screen(
        screen,
        cssProvider,
        Gtk.STYLE_PROVIDER_PRIORITY_USER,
    )
    window = Splash()
    window.set_decorated(False)
    window.set_resizable(False)
    window.set_keep_above(True)
    window.set_wmclass("Wmover", "wmover")
    window.show_all()
    window.connect("destroy", Gtk.main_quit)
    Gtk.main()


if __name__ == "__main__":
    try:
        subj = sys.argv[1]
    except IndexError:
        pass
    else:
        x_res = int(sys.argv[2])
        y_res = int(sys.argv[3])
        xoffset = int(sys.argv[4])
        yoffset = int(sys.argv[5])
        run_moverbar()
