import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { confirm } from '@nativescript/core/ui/dialogs';
import { Actions, ofActionSuccessful, Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { transitionOptions } from '~/constants/shared.constants';
import { PhoneContactService } from '~/core/services/phone-contact.service';
import { WarehouseItemReservationDetailOutput } from '../../entities/output/warehouseItemReservationDetailOutput';
import { CreateDeleteReservation, LoadReservationDetail } from '../../state-mgmt/reservation-borrowed-detail.action';
import { ReservationBorrowedDetailState } from '../../state-mgmt/reservation-borrowed-detail.state';
import { feedbackMessage } from '../../utils/feedback-messages';

@Component({
    selector: 'ReservationBorrowedDetail',
    moduleId: module.id,
    templateUrl: './reservation-borrowed-detail.component.html',
    styleUrls: ['./reservation-borrowed-detail.component.scss']
})

export class ReservationBorrowedDetailComponent implements OnInit {
    @Select(ReservationBorrowedDetailState.getReservationDetail) reservation$: Observable<WarehouseItemReservationDetailOutput>;
    @Select(ReservationBorrowedDetailState.isLoading) isLoading$: Observable<boolean>;
    reservation: WarehouseItemReservationDetailOutput;
    disabled: boolean;
    reservationState: string;
    othersIsLoading: boolean;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private phoneContactSrv: PhoneContactService,
        private actions$: Actions
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (RegExp('\/material\/reservationBorrowedDetail\/[0-9]+').test(this.router.url)) {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    onLoad() {
        this.store.dispatch(new LoadReservationDetail(this.route.snapshot.params['id']))
            .pipe(withLatestFrom(this.reservation$))
            .subscribe(([_, reservation]) => {
                this.reservation = reservation;
                this.reservationState = reservation.WarehouseItemReservationState;
                this.disabled = this.reservation.ID_WarehouseItemReservationState === 'waitsforconfirmation' ? false : true;
            }, err => {
                feedbackMessage(FeedbackType.Error, 'Načtení detailu rezervace', 'Nepodařilo se načíst detail rezervace.');
                console.log(err);
            });
    }

    ngOnInit(): void {
        this.othersIsLoading = false;

        this.actions$.pipe(ofActionSuccessful(CreateDeleteReservation)).subscribe(() => {
            feedbackMessage(FeedbackType.Success, 'Zrušení rezervace', `Rezervace byla zrušena.`);
            // this.routerExtensions.back();
            this.reservationState = 'Zrušená';
            this.disabled = true;
        });
    }

    onItemTap() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/materialDetail', this.reservation.ID_WarehouseItem], {transition: transitionOptions});
        }, 10);
    }

    onPersonTap() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['search/list/', this.reservation.ID_Submitter, false], {transition: transitionOptions});
        }, 10);
    }

    onWarehouseOriginTap() {
        if (this.reservation.ID_UnitOrigin !== this.reservation.ID_Unit) {
            feedbackMessage(FeedbackType.Error, 'Cizí sklad', 'Tento sklad nepatří do vaší jednotky.');

            return;
        }
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/warehouseDetail', this.reservation.ID_WarehouseOrigin], {transition: transitionOptions});
        }, 10);
    }

    onWarehouseTap() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/warehouseDetail', this.reservation.ID_Warehouse], {transition: transitionOptions});
        }, 10);
    }

    onCallTap() {
        this.phoneContactSrv.createCall(this.reservation.Phone);
    }

    onEmailTap() {
        this.phoneContactSrv.createEmail(this.reservation.Email);
    }

    deleteReservation() {
        this.othersIsLoading = true;
        const options = {
            title: 'Zrušení rezervace',
            message: 'Opravdu chcete zrušit rezervaci položky ' + this.reservation.WarehouseItem + '?',
            okButtonText: 'Ano',
            cancelButtonText: 'Ne'
        };
        this.othersIsLoading = false;
        confirm(options).then((result: boolean) => {
            if (result) {
                this.store.dispatch(new CreateDeleteReservation(this.reservation.ID));
            }
        });
    }

    updateReservation() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/reservationUpdate', this.reservation.ID], {transition: transitionOptions});
        }, 10);
    }

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

    get updateIcon() {
        return String.fromCharCode(0xf044);
    }

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