import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { ImageSource } from '@nativescript/core';
import { 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 { WarehouseItemDetailOutput } from '../../entities/output/warehouseItemDetailOutput';
import { WarehouseItemReservationAllOutput } from '../../entities/output/warehouseItemReservationAllOutput';
import {
    LoadItemDetail,
    LoadPhotoContent,
    LoadWarehouseItemReservationAll
} from '../../state-mgmt/material-detail.action';
import { MaterialDetailState } from '../../state-mgmt/material-detail.state';
import { feedbackMessage } from '../../utils/feedback-messages';

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

export class MaterialDetailComponent implements OnInit {
    @Select(MaterialDetailState.getwarehouseItemReservationAll) warehouseItemReservationAll$: Observable<WarehouseItemReservationAllOutput[]>;
    @Select(MaterialDetailState.getItemDetail) itemDetail$: Observable<WarehouseItemDetailOutput>;
    @Select(MaterialDetailState.getImageSource) photo$: Observable<ImageSource>;
    @Select(MaterialDetailState.isLoading) isLoading$: Observable<boolean>;
    item: WarehouseItemDetailOutput = null;
    reservations: WarehouseItemReservationAllOutput[];
    idDoc: number;
    photo: ImageSource = null;
    canBeLent: boolean;
    othersIsLoading: boolean;

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

    onLoad() {
        this.othersIsLoading = false;
        this.photo = null;
        this.idDoc = null;
        this.store.dispatch(new LoadItemDetail(this.route.snapshot.params['id']))
            .pipe(withLatestFrom(this.itemDetail$))

            .subscribe(([_, item]) => {
                this.item = item;
                this.store.dispatch(new LoadWarehouseItemReservationAll(this.item.ID, true))    // true because of only actual reservations

                .pipe(withLatestFrom(this.warehouseItemReservationAll$))
                .subscribe(([_, reservations]) => {
                    this.reservations = reservations.sort((a, b) => b.ID - a.ID);
                    for (let i = 0; i < this.reservations.length; i++) {
                        this.reservations[i].idForDisplay = i + 1;
                    }
                    this.canBeLent = this.reservations.length > 0 &&
                        this.reservations.find(obj => obj.ID_WarehouseItemReservationState === 'lent') === undefined;

                    if (this.item.ID_DocumentBig !== null) {
                        this.idDoc = this.item.ID_DocumentBig;
                    } else if (this.item.ID_Document !== null) {
                        this.idDoc = this.item.ID_Document;
                    } else if (this.item.ID_DocumentSmall !== null) {
                        this.idDoc = this.item.ID_DocumentSmall;
                    }

                    if (this.idDoc !== null) {
                        this.store.dispatch(new LoadPhotoContent(this.idDoc))
                        .pipe(withLatestFrom(this.photo$))
                        .subscribe(([_, photo]) => {
                            this.photo = photo;
                            console.log(this.photo.width + ', ' + this.photo.height);
                            console.log('joo, fotka je!');
                        }, err => {
                            this.photo = null;
                            this.idDoc = null;
                            feedbackMessage(FeedbackType.Error, 'Načtení fotografie', 'Nepodařilo se načíst fotografii položky.');
                            console.log(err);
                        });
                    }

                }, err => {
                    this.item = null;
                    this.photo = null;
                    this.idDoc = null;
                    feedbackMessage(FeedbackType.Error, 'Načtení rezervací', 'Nepodařilo se načíst rezervace položky.');
                    console.log(err);
                });
            }, err => {
                feedbackMessage(FeedbackType.Error, 'Načtení detailu položky', 'Nepodařilo se načíst detail položky.');
                console.log(err);
            });
    }

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

    updateItem() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/materialUpdate',
                this.item.ID,
                this.item.ID_Warehouse,
                this.item.ID_WarehouseItemCategory,
            this.item.ID_PurchaseType], {transition: transitionOptions});
        }, 10);
    }

    lendItem() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/materialLend', this.item.ID, this.item.DisplayName], {transition: transitionOptions});
        }, 10);
    }

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

    deleteItem() {
        this.othersIsLoading = true;
        setTimeout(() => {
            this.routerExtensions.navigate(['material/materialDelete', this.item.ID, this.item.DisplayName], {transition: transitionOptions});
        }, 10);
    }

    onCallTap(phone: string) {
        this.phoneContactSrv.createCall(phone);
    }

    onEmailTap(email: string) {
        this.phoneContactSrv.createEmail(email);
    }

    onBackButton(): void {

        this.routerExtensions.back();
    }

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

    get lendIcon() {
        return String.fromCharCode(0xf360);
    }

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