
/* Gnome Encfs Manager (GEncfsM)
 * Copyright (C) 2011 Moritz Molch <mail@moritzmolch.de>
 
 * 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 2 of the License, or
 * (at your option) 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, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

using Gtk;
using GnomeEncfsManager;
using GLib;
using Gee;

namespace GnomeEncfsManager {
    public class Preferences : GLib.Object {
        private static Window prefWindow;
        private static Builder builder;
        private static ulong sighandler;

        public static void show() {
            if (prefWindow != null)
                return;
        
            try {
                builder = new Builder();
                builder.add_from_file(get_glade_file("preferences.ui"));
                builder.connect_signals(null);

                update_window();
                
                sighandler = settings.changed.connect( () => {
                    update_window();
                });
                
                ((ToggleButton)builder.get_object("checkbutton_start_on_login")).set_active(
                                                                    autostart_get_enabled());
                
                prefWindow = (Window)builder.get_object("preferences");
                prefWindow.show_all();
                
                
            } catch (Error e) {
                stderr.printf("Could not load UI: %s\n", e.message);
            }
        }
        
        public static void update_window() {
            ((ToggleButton)builder.get_object("checkbutton_show_trayicon")).set_active(
                                                settings.get_boolean("show-trayicon"));

            ((ToggleButton)builder.get_object("checkbutton_start_minimized")).set_active(
                                                settings.get_boolean("start-minimized"));
                                                
            ((ToggleButton)builder.get_object("checkbutton_start_minimized")).set_sensitive(
                                                settings.get_boolean("show-trayicon"));
                                                
            ((ToggleButton)builder.get_object("checkbutton_tray_stash_groups")).set_active(
                                                settings.get_boolean("tray-stash-groups"));
                                                
            ((ToggleButton)builder.get_object("checkbutton_tray_stash_groups")).set_sensitive(
                                                settings.get_boolean("show-trayicon"));

            ((ToggleButton)builder.get_object("checkbutton_unmount_on_logout")).set_active(
                                                settings.get_boolean("unmount-on-logout"));

        }
        
        
        public static void on_close() {
            if (prefWindow == null)
                return;
        
            settings.disconnect(sighandler);
            prefWindow.destroy();
            prefWindow = (Window)null;
        }
        
        public static void on_start_on_login_toggled(ToggleButton source) {
            autostart_set_enabled(source.get_active());
        }
        
        public static void on_show_tray_icon_toggled(ToggleButton source) {
            settings.set_boolean("show-trayicon", source.get_active());
        }
        
        public static void on_start_hidden_to_tray(ToggleButton source) {
            settings.set_boolean("start-minimized", source.get_active());
        }
        
        public static void on_tray_stash_groups_toggled(ToggleButton source) {
            settings.set_boolean("tray-stash-groups", source.get_active());
        }
        
        public static void on_unmount_on_logout_toggled(ToggleButton source) {
            settings.set_boolean("unmount-on-logout", source.get_active());
        }
        
        public static bool autostart_get_enabled() {
            return FileUtils.test(Path.build_filename(get_autostart_path(),
                                    "gnome-encfs-manager.desktop"), FileTest.EXISTS);
        }

        public static void autostart_set_enabled(bool enabled) {
            if (enabled) {
                if (autostart_get_enabled()) {
                    return;
                }
            
                string desktop_entry_text=  """[Desktop Entry]
Exec=gnome-encfs-manager
Hidden=false
Icon=gnome-encfs-manager
Name=Gnome Encfs Manager
Type=Application
X-GNOME-Autostart-enabled=true
""";

                try {
                    var file = File.new_for_path (Path.build_filename(get_autostart_path(),
                                                            "gnome-encfs-manager.desktop"));
                                                            
                    if (!FileUtils.test(get_autostart_path(), FileTest.EXISTS)) {
                        Posix.mkdir(get_autostart_path(), 0700);
                    }

                    {
                        var file_stream = file.create (FileCreateFlags.NONE);
                        if (file.query_exists ()) {
                            var data_stream = new DataOutputStream (file_stream);
                            data_stream.put_string (desktop_entry_text);
                        }
                        else {
                        }

                    }
                } catch (Error e) {
                    stderr.printf ("Error: %s\n", e.message);
                }
            }
            else {
                if (!autostart_get_enabled()) {
                    return;
                }
                FileUtils.remove(Path.build_filename(get_autostart_path(),
                                            "gnome-encfs-manager.desktop"));
            }

			if (builder != null) {
            	((ToggleButton)builder.get_object("checkbutton_start_on_login")).set_active(
                                                               autostart_get_enabled());
            }
        }
        
        private static string get_autostart_path() {
        	return Path.build_filename(Environment.get_home_dir(), ".config", "autostart");
        }
        
        public static void on_advanced() {
        	PreferencesAdvanced adv_dialog = new PreferencesAdvanced();
            ((Window)adv_dialog).present();
            ((Window)adv_dialog).set_keep_above(true);
        	adv_dialog.run();
        	adv_dialog = (PreferencesAdvanced)null;
        }
    }
    
    public class PreferencesAdvanced : Dialog {
    	public const string options[] = {   "file_manager_command",
    						 				"mount_added_command",
    						 				"mount_removed_command"
    					   		 		};
		private HashMap<string, Entry> entries;
		private Entry entry_mount_dir_base;
		private Entry entry_force_traysystem;
    					   		 
		public PreferencesAdvanced() {
			this.title = _("Advanced preferences");
			this.border_width = 5;
			set_default_size (100, 100);
			create_widgets ();
			connect_signals ();
		}

		private void create_widgets () {
			entries = new HashMap<string, Entry> ();
		
			Grid grid = new Grid();
			
			var label = new Label("<a href=\"http://moritzmolch.com/1291\">" + _("Please visit this link to learn about GEncfsM scripts and scripting.") + "</a>");
			label.use_markup = true;
			label.set_line_wrap (true);
			label.xalign = 0;
			label.ypad = 5;
			label.margin_bottom = 8;
			grid.attach(label, 0,0,2,1);
			
			int i = 1;
			foreach (string s in options) {
				label = new Label(s + ":");
				label.xalign = 0;
				label.margin_right = 5;
				var entry = new Entry();
				entries[s] = entry;
				grid.attach(label, 0,i,1,1);
				grid.attach(entry, 1,i,1,1);
				i++;
			}
			
			label = new Label("mount_dir_base:");
			label.xalign = 0;
			label.margin_right = 5;
			entry_mount_dir_base = new Entry();
			grid.attach(label, 0,i,1,1);
			grid.attach(entry_mount_dir_base, 1,i,1,1);
			i++;
			
			label = new Label("force_traysystem:");
			label.xalign = 0;
			label.margin_right = 5;
			entry_force_traysystem = new Entry();
			grid.attach(label, 0,i,1,1);
			grid.attach(entry_force_traysystem, 1,i,1,1);
			i++;

			Gtk.Box content = get_content_area () as Gtk.Box;
			content.spacing = 10;
			content.pack_start (grid, false, true, 0);

			add_button (Gtk.Stock.CLOSE, Gtk.ResponseType.CLOSE);
			update();
			this.show_all();
		}

		private void connect_signals () {
			this.response.connect (on_response);
		}

		private void on_response (Gtk.Dialog source, int response_id) {
			GnomeEncfsManager.options.clear();
			foreach (var entry in entries.entries) {
				GnomeEncfsManager.options.set_string(entry.key, entry.value.get_text());
			}
			settings.set_string("advanced-options", GnomeEncfsManager.options.to_string());
			settings.set_string("mount-dir-base", entry_mount_dir_base.get_text());
			settings.set_string("force-traysystem", entry_force_traysystem.get_text());
			destroy();
		}
		
		private void update() {
			foreach (var entry in entries.entries) {
				entries[entry.key].set_text(GnomeEncfsManager.options.get_string(entry.key));
			}
			entry_mount_dir_base.set_text(settings.get_string("mount-dir-base"));
			entry_force_traysystem.set_text(settings.get_string("force-traysystem"));
		}
    }
}
