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

import com.liferay.fragment.model.FragmentEntryLink;
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 FragmentEntryLinkModelListener
	extends BaseModelListener<FragmentEntryLink> {

	@Override
	public void onAfterRemove(FragmentEntryLink fragmentEntryLink) {
		clearCache(fragmentEntryLink);
	}

	@Override
	public void onAfterUpdate(FragmentEntryLink fragmentEntryLink) {
		clearCache(fragmentEntryLink);
	}

	protected void clearCache(FragmentEntryLink fragmentEntryLink) {
		if (fragmentEntryLink == null) {
			return;
		}

		_fragmentRenderer.clearCache(
			fragmentEntryLink.getFragmentEntryLinkId());

		_fragmentRenderer.clearWidgetCache(
			fragmentEntryLink.getFragmentEntryLinkId());
	}

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

	private FragmentRenderer _fragmentRenderer;

}