import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PageRoute, RouterExtensions } from '@nativescript/angular';
import { Actions, ofActionSuccessful, Select, Store } from '@ngxs/store';
import { Feedback, FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { transitionOptions } from '~/constants/shared.constants';
import { MessageDetailOutput } from '~/pages/message/entities/output/messageDetailOutput';
import { CreateMessageUpdatedDelete, LoadMessageDetail } from '~/pages/message/state-mgmt/message-detail.actions';
import { MessageDetailState } from '~/pages/message/state-mgmt/message-detail.state';
import { switchMap, withLatestFrom } from 'rxjs/operators';

@Component({
    selector: 'MessageDetail',
    moduleId: module.id,
    templateUrl: './message-detail.component.html',
    styleUrls: ['./_message-detail.component.scss']
})
export class MessageDetailComponent implements OnInit {
    @Select(MessageDetailState.getMessageDetail) messageDetail$: Observable<MessageDetailOutput>;
    @Select(MessageDetailState.isLoading) isLoading$: Observable<boolean>;
    messageDetail: MessageDetailOutput;
    feedback: Feedback;

    constructor(
        private router: Router,
        private routerExtensions: RouterExtensions,
        private pageRoute: PageRoute,
        private store: Store,
        private actions$: Actions
    ) {
        // TODO Weird bug with webview on emulator when freshly logged in user tries to go to message detail app crashes with no error
        this.actions$
            .pipe(ofActionSuccessful(CreateMessageUpdatedDelete))
            .subscribe(() => {
                // TODO WHY IS CALLED TWICE?
                this.feedback.show({
                    title: 'SUCCESS',
                    type: FeedbackType.Success,
                    message: 'Zpráva byla smazaná.'
                });
                this.routerExtensions.navigate(['message/list'], { transition: transitionOptions });
            });
    }

    ngOnInit() {
        this.feedback = new Feedback();
        // TODO GET MESSAGEaLLwEB FROM STATE if is not set dispatch action
        this.pageRoute.activatedRoute
            .pipe(
                switchMap(activatedRoute => activatedRoute.params)
            )
            .forEach((params) => {
                this.store.dispatch(new LoadMessageDetail(+params['id']))
                    .pipe(withLatestFrom(this.messageDetail$)).subscribe(([_, detail]) => {
                        this.messageDetail = detail;
                    })
            });
    }

    onDeleteMessage(messageId: number) {
        this.store.dispatch(new CreateMessageUpdatedDelete(messageId, true));
    }

    onBackButton(): void {
        this.routerExtensions.back();
    }

    get trashIcon() {
        return String.fromCharCode(0xf2ed);
    }
}
