import {Injectable} from "@angular/core";
import {Actions, createEffect, ofType} from "@ngrx/effects";
import {fromAuthorize} from "../actions";
import {catchError, exhaustMap, map, of, switchMap} from "rxjs";
import {Account, MastodonApiAuthenticationService, RegisteredApp} from "projects/mastodon-api/src/public-api";
import {Store} from "@ngrx/store";
import {environment} from "../../../../../environments/environment";
import {NlNotificationService} from "../../../services/nl-notification.service";

@Injectable()
export class AuthorizationStateEffects {
    registerApplication$ = createEffect(() =>
        this.actions$.pipe(
            ofType(fromAuthorize.registerApplication),
            exhaustMap((action) =>
                this.mastodonApiAuthService
                    .createApp(action.instanceName, environment.appName, action.redirectUrl, environment.appWebsite)
                    .pipe(
                        map((registeredApp: RegisteredApp) => {
                            this.notificationService.success('Successfully registered the application with the instance', 'success');
                            return fromAuthorize.registerApplicationSuccess({
                                id: registeredApp.id,
                                appName: registeredApp.name,
                                website: registeredApp.website,
                                clientId: registeredApp.clientId,
                                clientSecret: registeredApp.clientSecret,
                            })
                        }),
                        catchError((error) => {
                            this.notificationService.danger('Could not register application. Please check the instance name.', 'warning');
                            return of(fromAuthorize.registerApplicationError({error}));
                        }),
                    )
            )
        )
    );

    getAccessToken$ = createEffect(() =>
        this.actions$.pipe(
            ofType(fromAuthorize.getAccessToken),
            switchMap((action) =>
                this.mastodonApiAuthService
                    .getAccessToken(action.instanceName!, action.clientId!, action.clientSecret!, action.redirectUrl!, action.code)
                    .pipe(
                        map(accessToken => {
                            return {action, accessToken};
                        })
                    )
            ),
            switchMap((result) =>
                this.mastodonApiAuthService
                    .verifyCredentials(result.action.instanceName, result.accessToken)
                    .pipe(
                        map((account: Account) => {
                            return {accessToken: result.accessToken, account};
                        })
                    )
            ),
            map((result) => {
                this.notificationService.success('User successfully authenticated', 'success');
                return fromAuthorize.getAccessTokenSuccess({accessToken: result.accessToken, account: result.account});
            }),
            catchError((error) => {
                console.error(error);
                this.notificationService.danger('Could not get access token', 'error');
                return of(fromAuthorize.getAccessTokenError());
            }),
        )
    );

    authorizeUser$ = createEffect(() =>
        this.actions$.pipe(
            ofType(fromAuthorize.authorizeUser),
            map((action) => {
                this.mastodonApiAuthService.authorizeUser(action.instanceName!, action.clientId!, action.redirectUrl!);
            })
        ), {dispatch: false});

    constructor(
        private store: Store,
        private actions$: Actions,
        private mastodonApiAuthService: MastodonApiAuthenticationService,
        private notificationService: NlNotificationService,
    ) {
    }
}
