﻿(function () {
	'use strict';

	angular.module('app').factory('smartTableService', smartTableService);

	smartTableService.$inject = ['__env', 'auth0Service', '$rootScope', '$http'];

	function smartTableService(__env, auth0Service, $rootScope, $http) {

		var service = new Object({
			downloadReport: downloadReport
		});

		return service;

		function downloadReport(objRequest, executeCallBack) {
			if (Autenthicated()) {
				$http.post(__env.apiUrl + __env.GenericUrl.postExportData, JSON.stringify(objRequest),
					{ responseType: __env.Header.responseBuffer })
					.then(function onSuccess(response) {
						var filename = response.headers(__env.Header.name);
						var contentType = response.headers(__env.Header.content);
						var file = new Blob([response.data], { type: contentType });
						saveAs(file, filename);
						if (typeof executeCallBack === "function") {
							executeCallBack();
						}
					}, function onError(response) {
						localMessage(null, __env.typeMessage.typeD, response);
					});
			}
		}

		//message and authenticated
		function localMessage(valueText, type, value) {
			params = __env.eventResponse();
			if (type === __env.typeMessage.typeW) {
				params.eventWarning = true;
			}
			else if (type === __env.typeMessage.typeD) {
				params.eventError = true;
			}
			else if (type === __env.typeMessage.typeS) {
				params.eventSuccess = true;
			}
			if (value !== null) {
				params.value = value;
			}
			if (valueText !== null) {
				params.text = valueText;
			}
			__env.Message($rootScope, params);
		}

		function Autenthicated() {
			if (!auth0Service.isAuthenticated()) {
				$state.go('login', { errors: auth0Service.gerErrorMessage() });
				return false;
			}
			return true;
		}

	}

})();