angular.module("c8y.parts.oauth").controller("OAuthCtrl",["$scope","$location","$window","$http","c8ySettings","c8yAuth","c8yUser","c8yTitle","c8yAlert","gettext",function(r,t,e,n,c,o,a,i,u,d){var l=t.search(),s=t.host(),h="developer.cumulocity.com",p=t.protocol(),y=t.port(),t=a.current(),f=e.location.pathname,g=null;function k(t){t=t.data;r.token=t.value}function m(t){t=t.data;u.danger("".concat(t.error,": ").concat(t.error_description))}function v(e){return _.keys(e).map(function(t){return"".concat(t,"=").concat(e[t])}).join("&")}function T(t){var e={},n=[],o="redirect"===t?h:s,r=80!==parseInt(y,10)&&443!==parseInt(y,10)?":".concat(y):"",o="".concat(p,"://").concat(o).concat(r);return e.tenant_id=g,"login"===t&&(_.assign(e,{redirect_uri:T("redirect"),response_type:"code"}),n=[o,"/tenant/oauth?",v(e)]),"token"===t&&(n=[o,"/tenant/oauth?"]),(n="redirect"===t?[o,f,"%23/oauth"]:n).join("")}function w(){return T("login")}t.then(function(t){var e;g=t.tenant,l.code?(t=l.code,e=T("token"),(t={redirect_uri:T("redirect"),grant_type:"authorization_code",code:t}).tenant_id=g,n({method:"POST",url:e,data:v(t),headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(function(t){var n,o,t=t.data;t.refresh_token&&(n=t.refresh_token,o="paypal",c.list().then(function(t){var e="createOption";(t||[]).forEach(function(t){return t.category!==o||!(e="updateOption")}),c[e]({category:o,key:"refreshToken",value:n}).then(function(){r.token=n,r.$emit("message",{type:"success",text:d("Token saved.")})})}))},m)):c.detail({category:"paypal",key:"refreshToken"}).then(k),r.getLoginUrl=w}),i.changeTitle({title:d("OAuth")})}]);