-- If a message is sent by gammu-smsd-inject, Kalkun won't display it.
-- However, if we create a 'trigger' on the addition of a message in outbox
-- that will create the corresponding record in user_oubox, kalkun will display
-- it. Display will be done either for a kalkun username of "smsd-inject", or
-- if that user doesn't exist, for user "kalkun".
-- It is not needed to do this for messages in "sentitems"
--
-- We have to be sure this trigger is not triggered if the message is sent
-- by kalkun the kalkun web interface.
--
-- Processing of incoming messages is managed by Kalkun's daemon which is triggered by
-- RunOnReceive in gammu-smsd config

CREATE OR REPLACE FUNCTION fn_outbox_item_inserted()
  RETURNS TRIGGER AS 
$$
DECLARE
    var_id_user integer := 1;
BEGIN
    IF (SELECT id_outbox FROM user_outbox WHERE id_outbox = NEW."ID") IS NULL THEN
    IF NEW."CreatorID" LIKE 'Gammu%' THEN
        SELECT (id_user) INTO var_id_user FROM "user" WHERE username = 'smsd-inject';
        IF var_id_user IS NULL THEN
            INSERT INTO user_outbox VALUES (NEW."ID",1);
        ELSE
            INSERT INTO user_outbox VALUES (NEW."ID",var_id_user);
        END IF;
    END IF;
    END IF;
    RETURN NEW;
END $$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS "outbox_item_inserted" ON "outbox";
CREATE TRIGGER "outbox_item_inserted" 
    AFTER INSERT 
    ON outbox
    FOR EACH ROW
    EXECUTE PROCEDURE fn_outbox_item_inserted();
