"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.getUser = undefined;

var _regenerator = require("babel-runtime/regenerator");

var _regenerator2 = _interopRequireDefault(_regenerator);

exports.handleAuthSaga = handleAuthSaga;

var _effects = require("redux-saga/effects");

var _actions = require("../actions");

var _services = require("../services");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _marked = /*#__PURE__*/_regenerator2.default.mark(handleAuthSaga);

var getUser = exports.getUser = function getUser(state) {
    return state.auth.user;
};

function handleAuthSaga() {
    var profile, user;
    return _regenerator2.default.wrap(function handleAuthSaga$(_context) {
        while (1) {
            switch (_context.prev = _context.next) {
                case 0:
                    profile = void 0;
                    _context.next = 3;
                    return (0, _effects.select)(getUser);

                case 3:
                    user = _context.sent;
                    _context.prev = 4;
                    _context.next = 7;
                    return (0, _effects.put)(_actions.authRoutine.request());

                case 7:
                    if (!(null === user)) {
                        _context.next = 11;
                        break;
                    }

                    _context.next = 10;
                    return (0, _effects.call)(_services.authRequest);

                case 10:
                    user = _context.sent;

                case 11:
                    if (!user) {
                        _context.next = 17;
                        break;
                    }

                    _context.next = 14;
                    return (0, _effects.call)(_services.userAttributes, user);

                case 14:
                    profile = _context.sent;
                    _context.next = 17;
                    return (0, _effects.put)(_actions.authRoutine.success({ user: user, profile: profile }));

                case 17:
                    _context.next = 23;
                    break;

                case 19:
                    _context.prev = 19;
                    _context.t0 = _context["catch"](4);
                    _context.next = 23;
                    return (0, _effects.put)(_actions.authRoutine.failure({ flash: { error: _context.t0.message } }));

                case 23:
                    _context.prev = 23;
                    _context.next = 26;
                    return (0, _effects.put)(_actions.authRoutine.fulfill());

                case 26:
                    return _context.finish(23);

                case 27:
                case "end":
                    return _context.stop();
            }
        }
    }, _marked, this, [[4, 19, 23, 27]]);
}