###
Module dependencies.
###

url = require 'url'

getRedirectSettings = (options, returnUrl) ->
#getRedirectSettings = (defaultRedirectUri, returnUrl, useReturnUrl) ->
  throw new Error '"options" parameter is required' if not options?

  defaultRedirectUri = options.redirectUrl
  useReturnUrl = options.useReturnUrl
  logoutUrl = options.logoutUrl

  portalLoginUrl = "/admin/site/Login.aspx"
  if returnUrl.indexOf(portalLoginUrl) isnt -1
    redirectUrl = "#{defaultRedirectUri}#{returnUrl}"
    return {
      returnUrl: returnUrl
      redirectUrl: redirectUrl
    }

  returnUrlParams = url.parse(returnUrl, true)
  returnUrl = returnUrlParams.pathname
  if returnUrlParams.query.previousUrl
    returnUrl = returnUrlParams.query.previousUrl

  #returnUrlParts = returnUrl.split('?')
  #returnUrl = returnUrlParts[0]
  #if returnUrlParts.length > 1
    #previousUrl = returnUrlParts[1].split('=')[1]

  #if(returnUrl is logoutUrl)
    #returnUrl = previousUrl

  #returnUrl = returnUrl.replace(/\/$/, '')

  redirectUrl = defaultRedirectUri
  redirectUrl = "#{defaultRedirectUri}#{returnUrl}" if useReturnUrl

  return {
    returnUrl: returnUrl
    redirectUrl: redirectUrl
  }

module.exports = getRedirectSettings
