package com.liferay.fragment.internal.model.listener;

import com.liferay.dynamic.data.mapping.model.DDMTemplate;
import com.liferay.fragment.renderer.FragmentRenderer;
import com.liferay.portal.kernel.model.BaseModelListener;
import com.liferay.portal.kernel.model.ModelListener;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

@Component(immediate = true, service = ModelListener.class)
public class DDMTemplateModelListener extends BaseModelListener<DDMTemplate> {

	@Override
	public void onAfterRemove(DDMTemplate ddmTemplate) {
		clearCache(ddmTemplate);
	}

	@Override
	public void onAfterUpdate(DDMTemplate ddmTemplate) {
		clearCache(ddmTemplate);
	}

	protected void clearCache(DDMTemplate ddmTemplate) {
		if (ddmTemplate == null) {
			return;
		}

		_fragmentRenderer.clearWidgetCache();
	}

	@Reference(
		target = "(fragment.renderer=fragmentEntryFragmentRenderer)",
		unbind = "-"
	)
	protected void setFragmentRenderer(FragmentRenderer fragmentRenderer) {
		_fragmentRenderer = fragmentRenderer;
	}

	private FragmentRenderer _fragmentRenderer;

}