/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.model;

import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.security.auth.PasswordModificationThreadLocal;
import com.liferay.portal.security.ldap.LDAPUserTransactionThreadLocal;
import com.liferay.portal.security.ldap.PortalLDAPExporterUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextThreadLocal;

import java.io.Serializable;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @author Minhchau Dang
 */
public abstract class BaseLDAPExportModelListener<T extends BaseModel<T>>
	extends BaseModelListener<T> {

	protected void exportToLDAP(final User user) throws Exception {
		if ((user == null) || user.isDefaultUser() ||
			LDAPUserTransactionThreadLocal.isOriginatesFromLDAP()) {

			return;
		}

		Callable<Void> callable = new Callable<Void>() {

			@Override
			public Void call() throws Exception {
				ServiceContext serviceContext =
					ServiceContextThreadLocal.getServiceContext();

				Map<String, Serializable> expandoBridgeAttributes = null;

				if (serviceContext != null) {
					expandoBridgeAttributes =
						serviceContext.getExpandoBridgeAttributes();
				}

				PortalLDAPExporterUtil.exportToLDAP(
					user, expandoBridgeAttributes);

				return null;
			}

		};

		boolean passwordPolicyEnabled = PrefsPropsUtil.getBoolean(
			user.getCompanyId(), PropsKeys.LDAP_PASSWORD_POLICY_ENABLED);

		if (passwordPolicyEnabled &&
			PasswordModificationThreadLocal.isPasswordModified()) {

			callable.call();
		}
		else {
			TransactionCommitCallbackRegistryUtil.registerCallback(callable);
		}
	}

}