'use strict';

define(function() {

  var AuthOidcCtrl = function(
      $scope,
      $location,
      PortalsFactory,
      ExtraAuthenticationFactory
  ) {

        $scope.redirectToAngularOidc = function(oidcConfig, oidcAngularServer) {

            let gotoParam = $location.search().goto;
            if(!gotoParam){
                gotoParam = "home"
            }
            const app = $location.search().app || 'admin';
            const portalId = PortalsFactory.getPortalId();

            const issuer = oidcConfig.parameters.issuer_url;
            const clientId = oidcConfig.parameters.clientId;

            window.location.replace(oidcAngularServer + '?'
            + 'issuer=' + encodeURIComponent(issuer)
            + '&kisorigin' + encodeURIComponent(window.location.origin)
            + '&clientId=' + encodeURIComponent(clientId)
            + '&portalid=' + encodeURIComponent(portalId)
            + '&app=' + encodeURIComponent(app)
            + '&goto=' + encodeURIComponent(gotoParam)
            );
        };

        let oidcAngularServer = "";
        const oidcAngularServerResponse = ExtraAuthenticationFactory.oidcangularserver();

        oidcAngularServerResponse.then(
            response => {
                oidcAngularServer = response.data;
            })
        .catch(function(error) {
            console.error('Error fetching OIDC Angular Address :', error);
        });

        const oidcConf = ExtraAuthenticationFactory.getalloidc();

        oidcConf.then(
            response => {
                const oidcConfigurations = response.data;

                if (oidcConfigurations && oidcConfigurations.length > 0) {

                  // To change if there's more than 1 OIDC used simultaneously
                  let chosenOidcConfig = oidcConfigurations[0];

                  // Timeout to prevent the redirection from immediately happening if oidc exist but is not authorized
                  setTimeout(() => {
                  const shortPath = $location.path().replace(/\//g, '');
                  if(shortPath === "loginoidc")
                    $scope.redirectToAngularOidc(chosenOidcConfig, oidcAngularServer)
                  }, 500);

                }
            })
        .catch(function(error) {
            console.error('Error fetching OIDC configuration :', error);
        });

    }

  AuthOidcCtrl.$inject = [
      '$scope',
      '$location',
      'PortalsFactory',
      'ExtraAuthenticationFactory'
  ];
  return AuthOidcCtrl;
});