Pith - rabbet
const Applet = imports.ui.applet;
const PopupMenu = imports.ui.popupMenu;
const St = imports.gi.St;
const GLib = imports.gi.GLib;
const Main = imports.ui.main;

const ICON_START = 'media-playback-start-symbolic';
const ICON_STOP = 'media-playback-stop-symbolic';
const ICON_APPLET = 'alarm-symbolic';

const BORDER_NORMAL = '#bbbbbb';
const BORDER_FOCUS = '#bbbbbb';
const BORDER_ERROR = '#880000';
const WARN_SECONDS = 30;
const COLOR_WARN = '#e5484d';

function MyApplet(metadata, orientation, panel_height, instance_id) {
    this._init(metadata, orientation, panel_height, instance_id);
}

MyApplet.prototype = {
    __proto__: Applet.TextIconApplet.prototype,

    _init: function(metadata, orientation, panel_height, instance_id) {
        Applet.TextIconApplet.prototype._init.call(this, orientation, panel_height, instance_id);

        this.instance_id = instance_id;
        this.timerId = null;
        this._focusIdleId = null;
        this.targetTime = 0;
        this.isRunning = false;
        this.lastTimeSet = "00:00";

        this._formatting = false; // guard re-entrant
        this._entryFocused = false;
        this._entryError = false;

        this.set_applet_icon_symbolic_name(ICON_APPLET);
        this.hide_applet_label(true); // inactive icon

        this.menuManager = new PopupMenu.PopupMenuManager(this);
        this.menu = new Applet.AppletPopupMenu(this, orientation);
        this.menuManager.addMenu(this.menu);

        this._buildMenu();

        this.menu.connect('open-state-changed', (menu, isOpen) => this._onMenuOpenChanged(isOpen));
    },

    _buildMenu: function() {
        let menuItem = new PopupMenu.PopupBaseMenuItem({ reactive: false });
        let box = new St.BoxLayout({ style: 'spacing: 6px;' });

        this.entry = new St.Entry({
            hint_text: "HH:MM",
            can_focus: true,
            style: this._entryStyle()
        });

        let ct = this.entry.clutter_text;
        ct.connect('text-changed', () => this._onTextChanged());
        ct.connect('activate', () => this._startTimer());
        ct.connect('key-focus-in', () => {
            this._entryFocused = true;
            this._updateEntryStyle();
        });
        ct.connect('key-focus-out', () => {
            this._entryFocused = false;
            this._updateEntryStyle();
        });

        this.actionIcon = new St.Icon({
            icon_name: ICON_START,
            icon_type: St.IconType.SYMBOLIC,
            icon_size: 16
        });

        this.actionButton = new St.Button({
            child: this.actionIcon,
            style_class: 'button',
            style: `border: 1px solid ${BORDER_NORMAL}; border-radius: 4px; ` +
                   `padding: 5px 7px;`,
            reactive: true,
            can_focus: true,
            track_hover: true
        });
        this.actionButton.connect('clicked', () => this._toggleTimer());

        box.add_child(this.entry);
        box.add_child(this.actionButton);
        menuItem.addActor(box);
        this.menu.addMenuItem(menuItem);
    },

    _entryStyle: function() {
        let color = this._entryError ? BORDER_ERROR
                  : this._entryFocused ? BORDER_FOCUS
                  : BORDER_NORMAL;
        return `width: 90px; font-family: monospace; padding: 5px 7px; ` +
               `border: 1px solid ${color}; border-radius: 4px;`;
    },

    _updateEntryStyle: function() {
        this.entry.set_style(this._entryStyle());
    },

    _onMenuOpenChanged: function(isOpen) {
        if (!isOpen) return;

        // keyboard focus
        if (this._focusIdleId) GLib.source_remove(this._focusIdleId);
        this._focusIdleId = GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
            this._focusIdleId = null;
            if (this.menu.isOpen) {
                global.stage.set_key_focus(this.entry);
                this.entry.clutter_text.set_selection(0, -1); // select all
            }
            return GLib.SOURCE_REMOVE;
        });
    },

    // digits only
    _onTextChanged: function() {
        if (this._formatting) return;

        let ct = this.entry.clutter_text;
        let raw = ct.get_text();
        let cursor = ct.get_cursor_position();   // -1 end
        if (cursor < 0) cursor = raw.length;

        let digitsBefore = raw.substring(0, cursor).replace(/\D/g, '').length;
        let digits = raw.replace(/\D/g, '').substring(0, 4);
        digitsBefore = Math.min(digitsBefore, digits.length);

        let formatted = digits.length > 2
            ? `${digits.substring(0, 2)}:${digits.substring(2)}`
            : digits;

        if (formatted !== raw) {
            this._formatting = true;
            ct.set_text(formatted);
            ct.set_cursor_position(digitsBefore > 2 ? digitsBefore + 1 : digitsBefore);
            this._formatting = false;
        }

        if (this._entryError) {
            this._entryError = false;
            this._updateEntryStyle();
        }
    },

    _toggleTimer: function() {
        if (this.isRunning) {
            this._stopTimer();
        } else {
            this._startTimer();
        }
    },

    _startTimer: function() {
        let input = this.entry.get_text();
        let target = this._computeTarget(input);

        if (target === null) {
            this._entryError = true;
            this._updateEntryStyle();
            return;
        }

        this._clearTimer();
        this.lastTimeSet = input;
        this.targetTime = target;
        this.isRunning = true;
        this.actionIcon.icon_name = ICON_STOP;
        this.hide_applet_label(false);

        this._tick();
        this.timerId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1, () => this._tick());
        this.menu.close();
    },

    _stopTimer: function() {
        this._clearTimer();
        this._reset();
    },

    _clearTimer: function() {
        if (this.timerId) {
            GLib.source_remove(this.timerId);
            this.timerId = null;
        }
    },

    _reset: function() {
        this.isRunning = false;
        this.targetTime = 0;
        this.actionIcon.icon_name = ICON_START;
        this._applet_label.set_style(null);
        this.set_applet_label('');
        this.hide_applet_label(true);
    },

    _tick: function() {
        let remaining = Math.ceil((this.targetTime - Date.now()) / 1000);

        if (remaining <= 0) {
            this.timerId = null;
            let alarmTime = this.lastTimeSet;
            this._reset();
            Main.notify("Rabbet Alarm", `Alarm time reached: ${alarmTime}`);
            return GLib.SOURCE_REMOVE;
        }

        this.set_applet_label(this._formatDisplay(remaining, this.lastTimeSet));
        this._applet_label.set_style(remaining <= WARN_SECONDS ? `color: ${COLOR_WARN};` : null);
        return GLib.SOURCE_CONTINUE;
    },

    // next occurrence
    _computeTarget: function(str) {
        let m = /^(\d{2}):(\d{2})$/.exec(str);
        if (!m) return null;

        let hours = parseInt(m[1], 10);
        let minutes = parseInt(m[2], 10);
        if (hours > 23 || minutes > 59) return null;

        let now = new Date();
        let target = new Date(now.getFullYear(), now.getMonth(), now.getDate(),
                              hours, minutes, 0, 0);
        if (target.getTime() <= now.getTime()) {
            target.setDate(target.getDate() + 1);
        }
        return target.getTime();
    },

    _formatDisplay: function(totalSec, lastSet) {
        let h = Math.floor(totalSec / 3600);
        let m = Math.floor((totalSec % 3600) / 60);
        let s = totalSec % 60;

        let pad = (num) => String(num).padStart(2, '0');
        return `${pad(h)}:${pad(m)}:${pad(s)} [${lastSet}]`;
    },

    on_applet_clicked: function() {
        this.menu.toggle();
    },

    on_applet_removed_from_panel: function() {
        this._clearTimer();
        if (this._focusIdleId) {
            GLib.source_remove(this._focusIdleId);
            this._focusIdleId = null;
        }
    }
};

function main(metadata, orientation, panel_height, instance_id) {
    return new MyApplet(metadata, orientation, panel_height, instance_id);
}