sap.ui.define([
	"computec/appengine/core/BaseController",
	"computec/appengine/ui/model/json/JSONModel"
], function (Controller, JSONModel) {
	"use strict";

	return Controller.extend("computec.appengine.pdc.controller.Download", {
		onInit: function () {
			var self = this;

			Controller.prototype.onInit.call(self);
			self.setPageName("Download page");

			var oViewData = {
				logoUrl: sap.ui.require.toUrl("computec/appengine/pdc/assets/pdclogo.png")
			};

			var oViewModel = new JSONModel(oViewData);
			self.setModel(oViewModel, "downloadModel");

			self._downloadData();
		},

		_downloadData: function () {
			var self = this;

			var sRequestUrl = "/api/PDC/Download/GetDownloadFiles";

			var oFilesModel = new JSONModel();
			oFilesModel.loadData(sRequestUrl);

			oFilesModel.attachRequestCompleted((oEvent) => {
				if (oEvent.getParameter("success") === false) {
					self.showMessageErrorDialog("[PDC] [Download.controller]" + " url: " + sRequestURL);
				}
			});

			oFilesModel.attachRequestFailed((oEvent) => {
				self.showMessageErrorDialog("[PDC] [Download.controller]" + " url: " + sRequestURL);
			});

			self.setModel(oFilesModel, "filesModel");
		},

		onLinkPress: async function (oEvent) {
			var oBindingContext = oEvent.getSource().getBindingContext("filesModel");
			var oData = oBindingContext.getObject();
			var sLink = oData.DownloadLink; 
			var oXhr = new XMLHttpRequest();

			oXhr.open("GET", sLink, true);
			oXhr.responseType = "blob";
			oXhr.onload = function () {
				var oLink = document.createElement("a");
				var sUrl = window.URL.createObjectURL(oXhr.response);
				oLink.href = sUrl;
				oLink.download = oData.FileName;
				oLink.click();
				window.URL.revokeObjectURL(sUrl);
			};
			oXhr.send();
		}
	});
});