#!/usr/bin/python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import os

# Modified by ianonavy. 24 August 2011


class wp_show_conf():
    """ Main class file. """

    def saveopts(self):
        """ Saves options to state file in home directory. """

        optsdir = os.path.join(os.path.expanduser('~'), '.wp-show')
        optsfile = os.path.join(os.path.expanduser('~'), '.wp-show', 'opts')

        if not os.path.exists(optsdir):
            os.makedirs(optsdir)

        f = open(optsfile, 'w')
        data = '\n'.join([self.path, str(self.timeout), self.enabled,
                            str(self.depth)])
        f.write(data)
        f.close()

    def get_fields(self):
        """ Gets the fields. """

        self.path = self.filechooserbutton.get_filename()
        self.timeout = self.spin_button.get_value_as_int() * 60  # min to sec
        self.enabled = str(self.check.get_active()).lower()
        self.depth = self.depth_select.get_value_as_int()

    def retrieve_fields(self):
        """ Retrieves the fields from the option file. """

        optsfile = os.path.join(os.path.expanduser('~'), '.wp-show', 'opts')

        if os.path.exists(optsfile):
            f = open(optsfile, 'r')
            data = f.readlines()
            self.path = data[0].strip('\n')
            self.timeout = int(data[1].strip('\n')) / 60  # sec to min
            self.enabled = (data[2].strip('\n')) == 'true'
            self.depth = int(data[3].strip('\n'))
            f.close()

        else:  # returns defaults
            self.path = os.path.expanduser('~')
            self.timeout = 10  # Changed default to 10 minutes.
            self.enabled = True
            self.depth = 3

    def setit(self, widget, dummy):
        """ Save the options. """

        self.get_fields()
        self.saveopts()
        request = ' '.join(['tools/install', str(self.timeout),
                             self.enabled, str(self.depth), self.path])
        os.system(request)

    def __init__(self):
        """ Main Gtk window definitions."""

        ROOT = os.path.dirname(os.path.realpath(__file__))

        # Create a new window.
        window = Gtk.Window()
        window.set_title("Gnome 3 Wp-Show")
        window.connect("delete_event", lambda w, e: Gtk.main_quit())
        window.set_border_width(5)
        window.set_default_size(320, 400)

        self.retrieve_fields()

        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        vbox.set_spacing(3)
        window.add(vbox)

        # Retrieve and set the artwork.
        artwork = Gtk.VBox()
        fileimage = os.path.join(ROOT, 'tools/artwork.png')
        window.set_icon_from_file(fileimage)
        image = Gtk.Image()
        image.set_from_file(fileimage)
        artwork.pack_start(image, True, True, 0)
        vbox.pack_start(artwork, True, True, 1)

        frame = Gtk.Frame()
        vbox.pack_start(frame, True, True, 1)
        frame.set_border_width(5)
        frame.set_shadow_type(Gtk.ShadowType.NONE)

        table = Gtk.Table(4, 2)
        table.set_border_width(3)
        table.set_row_spacings(4)
        table.set_col_spacings(6)

        # Wallpaper directory
        label = Gtk.Label('Wallpaper Directory: ')
        label.set_alignment(0, 0.5)
        table.attach_defaults(label, 0, 1, 0, 1)
        frame.add(table)

        self.filechooserbutton = Gtk.FileChooserButton()
        self.filechooserbutton.set_current_folder(self.path)
        self.filechooserbutton.set_tooltip_text('Browse to the folder '
                                                'containing your wallpapers.')
        table.attach_defaults(self.filechooserbutton, 1, 2, 0, 1)
        self.filechooserbutton.set_action(
            Gtk.FileChooserAction(2))

        # Timeout
        label = Gtk.Label('Timeout (minutes):  ')
        label.set_alignment(0, 0.5)
        table.attach_defaults(label, 0, 1, 1, 2)

        adjustment = Gtk.Adjustment(self.timeout, 1, 1440, 5, 15)
        self.spin_button = Gtk.SpinButton()
        self.spin_button.set_adjustment(adjustment)
        self.spin_button.set_numeric(True)
        self.spin_button.set_tooltip_text('Time between switch in minutes.')
        table.attach_defaults(self.spin_button, 1, 2, 1, 2)

        # Directory depth
        label = Gtk.Label('Directory Depth : ')
        label.set_alignment(0, 0.5)
        table.attach_defaults(label, 0, 1, 2, 3)

        adjustment1 = Gtk.Adjustment(self.depth, 1, 10, 1, 1)
        self.depth_select = Gtk.SpinButton()
        self.depth_select.set_adjustment(adjustment1)
        self.depth_select.set_numeric(True)
        self.depth_select.set_tooltip_text('Level to which the '
                                           'subdirectory must be scanned.')
        table.attach_defaults(self.depth_select, 1, 2, 2, 3)

        # Enabled checkbox
        label = Gtk.Label('Enabled? ')
        label.set_alignment(0, 0.5)
        table.attach_defaults(label, 0, 1, 3, 4)

        self.check = Gtk.CheckButton()
        self.check.set_tooltip_text('Enable or disable the slideshow.')
        self.check.set_active(self.enabled)
        table.attach(self.check, 1, 2, 3, 4, Gtk.AttachOptions(2),
                         Gtk.AttachOptions(1), 0, 0)

        frame = Gtk.Frame()
        hbox = Gtk.HBox()
        hbox.set_homogeneous(True)
        frame.add(hbox)
        frame.set_border_width(5)
        frame.set_shadow_type(Gtk.ShadowType.NONE)
        vbox.pack_start(frame, False, True, 0)

        button = Gtk.Button(stock=Gtk.STOCK_CLOSE)
        button.connect("clicked", lambda w: Gtk.main_quit())
        hbox.pack_start(button, False, True, 0)
        button.set_can_default(True)
        button.grab_default()

        button = Gtk.Button(stock=Gtk.STOCK_APPLY)
        button.connect("clicked", self.setit, None)
        hbox.pack_start(button, False, True, 0)

        window.show_all()


def main():
    Gtk.main()
    return 0


if __name__ == "__main__":
    wp_show_conf()
    main()
