namespace SwayNotificationCenter.Widgets {
    class ToggleButton : Gtk.ToggleButton {

        private bool _active;
        private string command;
        private string active_test;
        public ToggleButton (string label, string command, string active) {
            this.command = command;
            this.active_test = active;
            this.label = label;
            this._active = false;

            debug("ToggleButton created with test: %s", active);

            this.toggled.connect (on_toggle);
        }

        public void compute_state() {
            debug("compute_state");
            this.set_active(this.check_should_be_active());
        }

        private void set_active(bool active) {
            debug("set_active: %i", (int)active);
            if (active) {
                this.get_style_context ().add_class ("active");
                this._active = true;
            } else {
                this.get_style_context ().remove_class ("active");
                this._active = false;
            }
        }

        private void on_toggle (Gtk.ToggleButton tb) {
            debug("on_toggle");
            this.set_active(!this._active);
            BaseWidget.execute_command (command);
        }

        private bool check_should_be_active () {
            string stdout;
            string stderr;
            int end_status;
            Process.spawn_sync (
                "/",
                this.active_test.split (" "),
                Environ.get(),
                SpawnFlags.SEARCH_PATH,
                null,
                out stdout,
                out stderr,
                out end_status);
            return end_status == 0;
        }
    }
}
