CREATE TABLE work_buffers(
    id INTEGER NOT NULL PRIMARY KEY,
    node_id INTEGER,
    start INTEGER NOT NULL,
    stop INTEGER,
    offset INTEGER NOT NULL
        DEFAULT (strftime('%s','now','localtime') - strftime('%s','now')),
    gtime_start INTEGER,
    gtime_stop INTEGER,
    start_comment TEXT,
    stop_comment TEXT,
    billable BOOLEAN NOT NULL,
    FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE,
    CONSTRAINT start_stop_order CHECK(stop >= start),
    CONSTRAINT offset_check CHECK (offset BETWEEN -64800 AND 64800)
);


CREATE INDEX
    work_buffers_gtime_start_gtime_stop
ON
    work_buffers(gtime_start,gtime_stop)
;

CREATE TRIGGER
    work_buffers_bi_2
BEFORE INSERT ON
    work_buffers
FOR EACH ROW WHEN
    NEW.stop IS NULL AND EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
        WHERE
            wb.stop IS NULL
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot have two open work buffers');
END;


CREATE TRIGGER
    work_buffers_bi_1
BEFORE INSERT ON
    work_buffers
FOR EACH ROW WHEN
    -- intersects with existing buffer
    EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
        WHERE
            -- just checking the start time at insert
            NEW.start + NEW.offset > wb.gtime_start AND
            NEW.start + NEW.offset < wb.gtime_stop
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot overlap work_buffers (insert)');
END;


CREATE TRIGGER
    work_buffers_ai_1
AFTER INSERT ON
    work_buffers
FOR EACH ROW
BEGIN

    UPDATE
        work_buffers
    SET
        gtime_start = NEW.start + NEW.offset,
        gtime_stop  = NEW.stop + NEW.offset
    WHERE
        id = NEW.id
    ;

END;


CREATE TRIGGER
    work_buffers_bu_1
BEFORE UPDATE OF
    start,stop
ON
    work_buffers
FOR EACH ROW WHEN
    EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
        WHERE
        NOT (NEW.start + NEW.offset >= wb.gtime_stop OR
            NEW.stop + NEW.offset <= wb.gtime_start)
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot overlap work_buffers (update)');
END;


CREATE TRIGGER
    work_buffers_au_1
AFTER UPDATE OF
    stop
ON
    work_buffers
FOR EACH ROW WHEN
    NEW.stop IS NOT NULL
BEGIN

    UPDATE
        work_buffers
    SET
        gtime_stop = NEW.stop + NEW.offset
    WHERE
        id = NEW.id
    ;

END;
