#!/usr/bin/env python3
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import cwtools as cw
import sys

color_index = int(sys.argv[1])
initcolor = sys.argv[2]
subs = cw.subkeys
wintitle = "ClockWorks set " + subs[color_index] + " color"

"""
ClockWorks
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 <https://www.gnu.org/licenses/>.
"""


class ColorChooser(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title=wintitle)
        maingrid = Gtk.Grid()
        maingrid.set_border_width(10)
        self.set_focus()
        self.set_skip_taskbar_hint(True)
        self.add(maingrid)
        self.color = Gtk.ColorSelection()
        self.color.set_has_palette(False)
        currc = [n * 257 for n in cw.prepare_rgb(initcolor)]
        suggested = Gdk.Color(red=currc[0], green=currc[1], blue=currc[2])
        self.color.set_current_color(suggested)
        maingrid.attach(self.color, 0, 0, 1, 1)
        buttonbox = Gtk.Box()
        maingrid.attach(buttonbox, 0, 1, 1, 1)
        choose = Gtk.Button("Choose")
        choose.connect("clicked", self.set_newcolor)
        choose.set_size_request(90, 20)
        buttonbox.pack_end(choose, False, False, 0)
        cancel = Gtk.Button("Cancel")
        cancel.connect("clicked", self.close_window)
        cancel.set_size_request(90, 20)
        buttonbox.pack_end(cancel, False, False, 0)

    def set_newcolor(self, *args):
        newcolor = str(self.color.get_current_color()).split()
        rgb = [int(int(n) / 257) for n in [
            s.split("=")[1].replace(",", "").replace(")", "")
            for s in newcolor
        ]]
        hx = cw.rgb2hex(rgb[0], rgb[1], rgb[2])
        val_toset = subs[color_index]
        cw.save_togsettings(hx, val_toset)
        self.close_window()

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


def chooser():
    window = ColorChooser()
    window.connect("destroy", Gtk.main_quit)
    window.show_all()
    Gtk.main()


chooser()
