-- sql/actions/labels.sql
-- This file is part of Decimail; see http://decimail.org
-- (C) 2005 Philip Endecott
 
-- 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
-- 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 

drop table labels cascade;
drop table labeled_messages cascade;
drop view label_mailboxes cascade;
drop trigger labels_changed on labels cascade;
delete from actions where mailbox_pattern='Labels/%';

begin;

create table labels (
    username  text  not null,
    label     text  not null,
    primary key (username, label)
);

-- To make it possible to create new mailboxes under Labels/ there
-- must be at least one mailbox already present, since empty folders are
-- not found by Decimail's LIST command.  So you'll need to run something
-- like this:

-- insert into labels (username, label) values ('your-username-here', 'Example');


create table labeled_messages (
    username  text  not null,
    label     text  not null,
    msg_id    integer not null,
    primary key (username, label, msg_id),
    foreign key (username, label) references labels
        on delete cascade on update cascade,
    foreign key (msg_id) references messages
        on delete cascade
);


create view label_mailboxes as select
    username,
    ('Labels/' || label) as mailbox_name,
    ('select msg_id from labeled_messages '
      'where username=\'' || username || '\''
      'and label=\'' || label || '\'') as query
    from labels;


create trigger labels_changed
	after insert or update or delete on labels
	for each statement
	execute procedure update_mailboxes();


insert into actions (mailbox_pattern, create_action, delete_action,
                     rename_action, copy_action)
values ('Labels/%',
        'insert into labels (username,label) values (''$U'',replace(''$MB'',''Labels/'',''''))',
        'delete from labels where username=''$U'' and label=replace(''$MB'',''Labels/'','''')',
        'update labels set label=replace(''$NMB'',''Labels/'','''') where username=''$U'' and label=replace(''$OMB'',''Labels/'','''')',
        'insert into labeled_messages(username,label,msg_id) values (''$U'', replace(''$MB'',''Labels/'',''''), $MSG_ID)');

end;
