-- sql/actions/keywords.sql
-- This file is part of Decimail; see http://decimail.org
-- (C) 2007 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 keywords cascade;
drop view keywords_mailboxes cascade;
drop trigger keywords_changed on keywords cascade;
delete from actions where mailbox_pattern='Keywords/%';

begin;

create table keywords (
    username  text  not null,
    keyword   text  not null,
    primary key (username, keyword)
);

-- Unless you mail client allows you to create new mailboexes by specifying
-- a complete path (as Decimail Webmail does), to make it possible to create 
-- new mailboxes under Keywords/ there must be at least one mailbox already 
-- present, since empty folders are not found by Decimail's LIST command.  
-- You'll need to run something like this:

-- insert into keywords (username, keyword) values ('your-username-here', 'Hello');


create view keyword_mailboxes as select
    username,
    ('Keywords/' || keyword) as mailbox_name,
    ('select pt.msg_id from part_tsearch pt join u_messages m using(msg_id) '
      'where pt.data_tsidx @@ to_tsquery(''default'',''' || keyword || ''')') as query
    from keywords;


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


insert into actions (mailbox_pattern, create_action, delete_action,
                     rename_action)
values ('Keywords/%',
        'insert into keywords (username,keyword) values (''$U'',replace(''$MB'',''Keywords/'',''''))',
        'delete from keywords where username=''$U'' and keyword=replace(''$MB'',''Keywords/'','''')',
        'update keywords set keyword=replace(''$NMB'',''Keywords/'','''') where username=''$U'' and keyword=replace(''$OMB'',''Keywords/'','''')');


end;
