import {createReducer, on} from "@ngrx/store";
import {initialState} from "../authentication-state";
import {fromAuthorize} from "../actions";

export const authenticationStateReducer = createReducer(
    initialState,
    on(fromAuthorize.registerApplication, (_state, {instanceName, redirectUrl}) => {
        return {
            ..._state,
            registeringApplication: true,
            instanceName,
            redirectUrl,
        };
    }),
    on(fromAuthorize.registerApplicationSuccess, (_state, {id, appName, website, clientId, clientSecret}) => {
        return {
            ..._state,
            registeringApplication: false,
            applicationRegistered: true,
            id,
            appName,
            website,
            clientId,
            clientSecret,
        };
    }),
    on(fromAuthorize.registerApplicationError, (_state) => {
        return {
            ..._state,
            registeringApplication: false,
            applicationRegistered: false,
        };
    }),
    on(fromAuthorize.logout, (_state) => {
        return {
            ...initialState,
        };
    }),
    on(fromAuthorize.authorizeUser, (_state) => {
        return {
            ..._state,
            authorizingUser: true,
        }
    }),
    on(fromAuthorize.getAccessTokenSuccess, (_state, {accessToken, account}) => {
        return {
            ..._state,
            accessToken,
            account,
            authorizingUser: false,
        };
    }),
    on(fromAuthorize.getAccessTokenError, (_state) => {
        return {
            ..._state,
            authorizingUser: false,
        };
    }),
);
