sap.ui.define([
	"sap/ui/base/Object",
	"sap/base/util/extend",
	"sap/suite/ui/generic/template/genericUtilities/controlHelper",
	"sap/ui/core/Element",
	"sap/ui/core/InvisibleText"
	], function(BaseObject, extend, controlHelper, Element, InvisibleText) {
		"use strict";

		function getMethods(oTemplateUtils) {

			function fnSetHeaderSmartFormAriaLabelBy(oFirstSubSection) {
				var oSubSectionInfoObject = oTemplateUtils.oInfoObjectHandler.getControlInformation(oFirstSubSection.getId());
				oFirstSubSection.getBlocks().concat(oFirstSubSection.getMoreBlocks())
					.reduce(function(accBlock, currentBlock) {
						if (!currentBlock.getContent || !currentBlock.getContent() || !currentBlock.getContent().length) {
							return accBlock;
						}
						currentBlock.getContent().reduce(function(accContent, currentContent) {
							if (controlHelper.isSmartForm(currentContent)) {
								accContent.push(currentContent); // collect all SubSections SmartForms
							}
							return accContent;
						}, accBlock);
						return accBlock;
					}, [])
					.forEach(function(entry) {
						if (!oSubSectionInfoObject || (entry.getGroups().length === 1 && entry.getGroups()[0].getTitle && !entry.getGroups()[0].getTitle())) {
							// Case: header is editable. manifest.json, editableHeaderContent=true
							var sInvisibleTextID = `${entry.getId()}-ariaLabelBy-InvisibleText`,
								oInvisibleText = Element.getElementById(sInvisibleTextID);
							if (!oInvisibleText) {
								var customData = !entry.getCustomData() ? [] : entry.getCustomData().filter(function(entry) {return entry.getKey() === "smartFormAriaLabel";});
								if (customData.length && customData[0].getValue()) {
									oInvisibleText = new InvisibleText({id : sInvisibleTextID, text: customData[0].getValue()}).toStatic();
								}
							}
							if (oInvisibleText) {
								entry._suggestTitleId(oInvisibleText.getId()); // set Section title id that will be used for aria
							}
							return;
						}
					});
			}

			// public instance methods
			return {
				setHeaderSmartFormAriaLabelBy: fnSetHeaderSmartFormAriaLabelBy //
			};
		}

		return BaseObject.extend("sap.suite.ui.generic.template.ObjectPage.controller.SectionTitleHandler", {
			constructor: function(oController, oObjectPage, oTemplateUtils) {
				extend(this, getMethods(oController, oObjectPage, oTemplateUtils));
			}
		});
	});
