import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
import { actionCreator } from '@ema/rx';
import { Util } from '@ema/core';
const NAME_CHANGED = 'NAME_CHANGED';
const GITHUB_FOLLOWERS_LOADING = 'GITHUB_FOLLOWERS_LOADING';
const GITHUB_FOLLOWERS_LOADED = 'GITHUB_FOLLOWERS_LOADED';
export const initialState = { appId: '@ema/js-base', timestamp: Util.getTimeStamp(), config: {} };
export const changeName = actionCreator((payload) => {
    return {
        type: NAME_CHANGED,
        payload
    };
});
export const loadGithubFollowers = actionCreator((payload) => {
    const url = `https://api.github.com/users/${payload.username}/followers`;
    return {
        type: GITHUB_FOLLOWERS_LOADING,
        payload: ajax(url).pipe(map((xhr) => map(xhr.response, 'login')), map((followers) => ({
            type: 'GITHUB_FOLLOWERS_LOADED',
            payload: followers
        })))
    };
});
export default function reducer(state, action) {
    switch (action.type) {
        case NAME_CHANGED:
            return Object.assign({}, state, { isLoading: false, timestamp: Util.getTimeStamp(), name: action.payload });
        case GITHUB_FOLLOWERS_LOADING:
            return Object.assign({}, state, { isLoading: true });
        case GITHUB_FOLLOWERS_LOADED:
            return Object.assign({}, state, { isLoading: false, users: action.payload });
        default:
            return state;
    }
}
