/*
	Copyright (c) 2010 by Dennis Schridde

	This file is part of dovecot-metadata.

	dovecot-metadata is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	dovecot-metadata 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 Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with dovecot-metadata.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "metadata-mail-user-module-private.h"

struct metadata_mail_user_module metadata_mail_user_module =
	MODULE_CONTEXT_INIT(&mail_user_module_register);

static void metadata_mail_user_deinit(struct mail_user *user) {
	struct metadata_mail_user *muser = METADATA_USER_CONTEXT(user);
	if (muser == NULL) {
		i_error("metadata: found NULL user, can't deinit it");
		return;
	}

	if (muser->dict != NULL) {
		dict_deinit(&muser->dict);
	}

	if (muser->set != NULL) {
		metadata_settings_deinit(&muser->set);
	}

	return muser->module_ctx.super.deinit(user);
}

void metadata_mail_user_created(struct mail_user *user) {
	struct metadata_mail_user *muser = p_new(user->pool, struct metadata_mail_user, 1);
	muser->module_ctx.super = user->v;
	user->v.deinit = metadata_mail_user_deinit;

	metadata_settings_init(&muser->set, user);

	if (muser->set->dict_uri != NULL) {
#if DOVECOT_PREREQ(2,2)
		dict_init(muser->set->dict_uri, DICT_DATA_TYPE_STRING, user->username, user->set->base_dir, &muser->dict, NULL);
#else
		muser->dict = dict_init(muser->set->dict_uri, DICT_DATA_TYPE_STRING, user->username, user->set->base_dir);
#endif
		if (muser->dict == NULL)
			i_error("metadata: dict_init(%s) failed", muser->set->dict_uri);
	}

	MODULE_CONTEXT_SET(user, metadata_mail_user_module, muser);
}
