package ru.systematic.cisstat.portlet.toolbar.contributor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletURL;

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

import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Group;
import com.liferay.portal.kernel.model.Layout;
import com.liferay.portal.kernel.portlet.LiferayPortletResponse;
import com.liferay.portal.kernel.portlet.LiferayWindowState;
import com.liferay.portal.kernel.portlet.toolbar.contributor.BasePortletToolbarContributor;
import com.liferay.portal.kernel.portlet.toolbar.contributor.PortletToolbarContributor;
import com.liferay.portal.kernel.service.GroupLocalService;
import com.liferay.portal.kernel.servlet.taglib.ui.MenuItem;
import com.liferay.portal.kernel.servlet.taglib.ui.URLMenuItem;
import com.liferay.portal.kernel.theme.PortletDisplay;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.MapUtil;
import com.liferay.portal.kernel.util.Portal;
import com.liferay.portal.kernel.util.ResourceBundleUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portlet.asset.util.AssetUtil;

import ru.systematic.cisstat.constants.VideoNewsPortletKeys;
import ru.systematic.cisstat.portlet.display.context.VideoNewsDisplayContext;




@Component(
		immediate = true,
		property = {
			"javax.portlet.name=" + VideoNewsPortletKeys.VideoNews,
			"mvc.path=-", "mvc.path=/view.jsp"
		},
		service = {
			VideoNewsPortletToolbarContributor.class,
			PortletToolbarContributor.class
		}
	)
public class VideoNewsPortletToolbarContributor extends BasePortletToolbarContributor {
	
	
	protected void addPortletTitleAddAssetEntryMenuItems(
			List<MenuItem> menuItems, PortletRequest portletRequest,
			PortletResponse portletResponse)
		throws Exception {

		ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
			WebKeys.THEME_DISPLAY);

		Layout layout = themeDisplay.getLayout();
		PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

		String portletName = portletDisplay.getPortletName();
		
		VideoNewsDisplayContext assetPublisherDisplayContext =
				new VideoNewsDisplayContext(
					portletRequest, portletResponse,
					portletRequest.getPreferences());

			if (!assetPublisherDisplayContext.isShowAddContentButton() ||
				layout.isLayoutPrototypeLinkActive()
				)
				//||
				//portletName.equals(VideoNewsPortletKeys.HIGHEST_RATED_ASSETS) ||
				//portletName.equals(VideoNewsPortletKeys.MOST_VIEWED_ASSETS) ||
				//portletName.equals(VideoNewsPortletKeys.RELATED_ASSETS))
			{

				return;
			}
			
			Map<Long, Map<String, PortletURL>> scopeAddPortletURLs =
					assetPublisherDisplayContext.getScopeAddPortletURLs(1);

				if (MapUtil.isEmpty(scopeAddPortletURLs)) {
					return;
				}

				if (scopeAddPortletURLs.size() == 1) {
					Set<Map.Entry<Long, Map<String, PortletURL>>> entrySet =
						scopeAddPortletURLs.entrySet();

					Iterator<Map.Entry<Long, Map<String, PortletURL>>> iterator =
						entrySet.iterator();

					Map.Entry<Long, Map<String, PortletURL>> scopeAddPortletURL =
						iterator.next();

					long groupId = scopeAddPortletURL.getKey();

					Map<String, PortletURL> addPortletURLs =
						scopeAddPortletURL.getValue();

					for (Map.Entry<String, PortletURL> entry :
							addPortletURLs.entrySet()) {

						URLMenuItem urlMenuItem = _getPortletTitleAddAssetEntryMenuItem(
							themeDisplay, assetPublisherDisplayContext, groupId,
							entry.getKey(), entry.getValue());

						menuItems.add(urlMenuItem);
					}

					return;
				}

				URLMenuItem urlMenuItem = new URLMenuItem();

				Map<String, Object> data = new HashMap<>();

				data.put(
					"id", HtmlUtil.escape(portletDisplay.getNamespace()) + "editAsset");

				ResourceBundle resourceBundle = ResourceBundleUtil.getBundle(
					"content.Language", themeDisplay.getLocale(), getClass());

				String title = LanguageUtil.get(
					resourceBundle, "add-content-select-scope-and-type");

				data.put("title", title);

				urlMenuItem.setData(data);

				urlMenuItem.setLabel(title);

				LiferayPortletResponse liferayPortletResponse =
					_portal.getLiferayPortletResponse(portletResponse);

				PortletURL portletURL = liferayPortletResponse.createRenderURL();

				portletURL.setParameter("mvcPath", "/add_asset_selector.jsp");
				portletURL.setParameter("redirect", themeDisplay.getURLCurrent());
				portletURL.setWindowState(LiferayWindowState.POP_UP);

				urlMenuItem.setURL(portletURL.toString());

				urlMenuItem.setUseDialog(true);

				menuItems.add(urlMenuItem);
			
			
	}
	
	private URLMenuItem _getPortletTitleAddAssetEntryMenuItem(
			ThemeDisplay themeDisplay,
			VideoNewsDisplayContext assetPublisherDisplayContext, long groupId,
			String className, PortletURL portletURL) {

			URLMenuItem urlMenuItem = new URLMenuItem();

			Map<String, Object> data = new HashMap<>();

			PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

			data.put(
				"id", HtmlUtil.escape(portletDisplay.getNamespace()) + "editAsset");
			
			
			String message = AssetUtil.getClassNameMessage(className, themeDisplay.getLocale());

			String title = LanguageUtil.format(
				themeDisplay.getLocale(), "new-x", message, false);

			data.put("title", title);

			urlMenuItem.setData(data);

			urlMenuItem.setLabel(HtmlUtil.escape(message));

			long curGroupId = groupId;

			Group group = _groupLocalService.fetchGroup(groupId);
			
			// TODO Доделать Ильдар!
			/*AssetRendererFactory<?> assetRendererFactory =
				AssetRendererFactoryRegistryUtil.getAssetRendererFactoryByClassName(
					AssetUtil.getClassName(className));*/

			/*if (!group.isStagedPortlet(assetRendererFactory.getPortletId()) &&
				!group.isStagedRemotely()) {*/
			if(!group.isStagedRemotely()) {
				curGroupId = group.getLiveGroupId();
			}
			
			// TODO Доделать Ильдар

			boolean addDisplayPageParameter = AssetUtil.isDefaultAssetPublisher(themeDisplay.getLayout(), portletDisplay.getId(),assetPublisherDisplayContext.getPortletResource());

			String url = "nnnnnnnnnnnnnnnnnnnnnn";// AssetUtil.getAddURLPopUp(curGroupId, themeDisplay.getPlid(), portletURL,assetRendererFactory.getPortletId(), addDisplayPageParameter,themeDisplay.getLayout());

			urlMenuItem.setURL(url);

			urlMenuItem.setUseDialog(true);

			return urlMenuItem;
		}

	@Override
	protected List<MenuItem> getPortletTitleMenuItems(PortletRequest portletRequest, PortletResponse portletResponse) {
		// TODO Auto-generated method stub
		List<MenuItem> menuItems = new ArrayList<>();

		try {
			addPortletTitleAddAssetEntryMenuItems(
				menuItems, portletRequest, portletResponse);
		}
		catch (Exception e) {
			_log.error("Unable to add folder menu item", e);
		}

		return menuItems;
	}
	
	
	private static final Log _log = LogFactoryUtil.getLog(
			VideoNewsPortletToolbarContributor.class);

	private GroupLocalService _groupLocalService;
	
	@Reference
	private Portal _portal;

}
