'use strict';

angular.module('yololiumApp')
  .controller('MyAccountController', [
    '$scope'
  , '$location'
  , '$http'
  , 'DaplieApiConfig'
  , 'DaplieApiSession'
  , 'DaplieApiRequest'
  //, 'LdsAccount'
  , function ($scope, $location, $http, DaplieApiConfig, DaplieApiSession, DaplieApiRequest, LdsAccount) {
    var scope = this;

    function init(session) {
      if (!session || session.message) {
        scope.session = null;
        scope.account = null;
        scope.accounts = null;
        $location.url('/');
        return;
      }

      scope.session = session;
      scope.accounts = session.accounts;
      scope.account = DaplieApiSession.account(session);

      console.log('session', session);
      return DaplieApiRequest.profile(session).then(function (profile) {
        return LdsAccount.verifyAccount(session, profile);
      });
    }

    scope.showLoginModal = function () {
      // TODO profile manager
      return DaplieApiSession.openAuthorizationDialog();
    };

    scope.logout = function () {
      // TODO which token(s) to destroy?
      return DaplieApiSession.logout();
    };

    DaplieApiSession.checkSession().then(init, init).catch(init);
    DaplieApiSession.onLogin($scope, init);
    DaplieApiSession.onLogout($scope, init);
  }]);
