text: 'use strict';
  
  var loggingUtils = require('./logger');
  var logger = loggingUtils.getLogger('/Subscription');
  var urlUtils = require('../utils/url-utils');
  var xsenv = require('@sap/xsenv');
  var xssec = require('@sap/xssec');
  var uaaUtils = require('./uaa-utils');
  var urijs = require('urijs');
  
  exports.getDependencies = getDependencies;
  exports.checkScopes = checkScopes;
  exports.getApplicationURL = getApplicationURL;
  exports.getError = getError;
  exports.getCallbackPath = getCallbackPath;
  
  function checkScopes(req, cb){
    try {
      var token = getToken(req);
      var ownUAACredentials = xsenv.serviceCredentials({label: 'xsuaa'});
      xssec.createSecurityContext(token, ownUAACredentials, function (err, ctx) {
        if (err) {
          cb(err, null);
        } else if (!findCallbackScope(ctx)) {
          logger.error('Missing the expected scope - Callback - in the call to create subscription');
          var error = getError('Forbidden - Missing the expected scope', 403);
          cb(error, null);
        } else {
          cb(null, true);
        }
      });
    } catch (error) {
      cb (error);
    }
  }
  
  function findCallbackScope(ctx){
    if (process.env.SAAS_APPROUTER){
      return true;
    } else {
      return ctx.checkLocalScope('Callback');
    }
  }
  
  function getToken (req){
    var authorization = req.headers.authorization;
    if (!authorization) {
      logger.error('Missing Authorization header');
      throw getError('Missing Authorization header', 401);
    }
    var parts = authorization.split(' ');
    if (parts.length < 2) {
      logger.error('Invalid Authorization header format');
      throw getError('Invalid Authorization header format', 400);
    }
    var scheme = parts[0];
    var token = parts[1];
  
    if (scheme.toLowerCase() !== 'bearer') {
      logger.error('Authorization header is not a Bearer token');
      throw getError('Authorization header is not a Bearer token', 401);
    }
    return token;
  }
  
  
  function getApplicationURL  (req, cb){
    var error = null;
    if (!req.body){
      error = getError('Bad request: Missing body', 400);
      return cb(error);
    }
  
    var subdomain = req.body.subscribedSubdomain;
    if (!subdomain) {
      error = getError('Bad request: Missing subscribedSubdomain', 400);
      return cb(error);
    }
  
    uaaUtils.getUaaConfig(req, function (err, uaaOptions) {
      if (err) {
        return cb(err);
      }
      if (!uaaOptions) {
        return cb('Invalid UAA options');
      }
  
      if (uaaOptions.tenantmode !== 'shared'){
        error = getError('Tenant mode should be shared', 500);
        return cb(error);
      }
      var proto = req.headers['x-forwarded-proto'] || req.protocol;
      var url = proto + '://' + urlUtils.getRedirectHost(req).replace(uaaOptions.tenant, subdomain);
  
      return cb(null, url);
    });
  }
  
  function getError(errorStr, status){
    var error = new Error(errorStr);
    error.status = status;
    logger.error(errorStr);
    return error;
  }
  
  function getDependencies(){
    var dependenciesArray = [];
    var appId = null;
    var appName = null;
    var xsappname = null;
    var services = xsenv.readServices();
    for (var service in services) {
      xsappname = appId = appName = null;
      var svcName = services[service].label;
  
      var cred = services[service].credentials;
      if (svcName === 'destination' || svcName === 'connectivity'){
        appId = cred.xsappname;
        appName = svcName;
      } else if (cred.saasregistryappname){
        appId = cred.uaa.xsappname;
        appName = cred.saasregistryappname;
      } else if (cred.saasregistryenabled){
        xsappname = cred.uaa.xsappname;
      }
      var obj = null;
      if (appId && appName) {
        obj = {'appId': appId, 'appName': appName};
      } else if (xsappname){
        obj = {'xsappname': xsappname};
      }
      if (obj){
        dependenciesArray.push(obj);
      }
    }
    return dependenciesArray;
  }
  
  function getCallbackPath(){
    var callBackPath = {
      getDependenciesPath: '/callback/v1.0/dependencies',
      onSubscriptionPrefix: '/callback/v1.0/tenants'
    };
    try {
      var credentials = xsenv.serviceCredentials({label: 'saas-registry'});
      var appUrls = credentials.appUrls;
      if (appUrls) {
        var appUrlsJson = JSON.parse(appUrls);
        var parsedUrl = urijs.parse(appUrlsJson.getDependencies);
        callBackPath.getDependenciesPath = parsedUrl.path;
        parsedUrl = urijs.parse(appUrlsJson.onSubscription);
        let index = parsedUrl.path.indexOf('/{tenantId}');
        if (index > 0){
          parsedUrl.path = parsedUrl.path.substring(0,index);
        }
        callBackPath.onSubscriptionPrefix = parsedUrl.path;
      }
    } catch (e){
      return callBackPath;
    }
    return callBackPath;
  }