import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { WarehouseDetailOutput } from '../../entities/output/warehouseDetailOutput';
import { WarehouseUpdateOutput } from '../../entities/output/warehouseUpdateOutput';
import { CreateWarehouseUpdate, LoadWarehouseDetail } from '../../state-mgmt/warehouse-update.action';
import { WarehouseUpdateState } from '../../state-mgmt/warehouse-update.state';
import { feedbackMessage } from '../../utils/feedback-messages';

@Component({
    selector: 'WarehouseUpdate',
    moduleId: module.id,
    templateUrl: './warehouse-update.component.html',
    styleUrls: ['./warehouse-update.component.scss']
})

export class WarehouseUpdateComponent implements OnInit {
    @Select(WarehouseUpdateState.getWarehouseDetail) warehouse$: Observable<WarehouseDetailOutput>;
    @Select(WarehouseUpdateState.getWarehouseUpdate) warehouseUpdate$: Observable<WarehouseUpdateOutput>;
    @Select(WarehouseUpdateState.isLoading) isLoading$: Observable<boolean>;

    @ViewChild('name', {static: true}) name: ElementRef;
    @ViewChild('street', {static: true}) street: ElementRef;
    @ViewChild('city', {static: true}) city: ElementRef;
    @ViewChild('postcode', {static: true}) postcode: ElementRef;
    @ViewChild('note', {static: true}) note: ElementRef;

    warehouse: WarehouseDetailOutput;
    othersIsLoading: boolean;

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

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadWarehouseDetail(this.route.snapshot.params['id']))
            .pipe(withLatestFrom(this.warehouse$))
            .subscribe(([_, warehouse]) => {
                this.warehouse = warehouse;
                this.fillTextFields(this.warehouse);
            }, err => {
                feedbackMessage(FeedbackType.Error, 'Načtení detailu skladu', 'Nepodařilo se načíst detail skladu.');
                console.log(err);
            });
    }

    fillTextFields(warehouse: WarehouseDetailOutput) {
        this.othersIsLoading = true;
        this.name.nativeElement.text = warehouse.DisplayName ? warehouse.DisplayName : '';
        this.street.nativeElement.text = warehouse.Street ? warehouse.Street : '';
        this.city.nativeElement.text = warehouse.City ? warehouse.City : '';
        this.postcode.nativeElement.text = warehouse.Postcode ? warehouse.Postcode : '';
        this.note.nativeElement.text = warehouse.Note ? warehouse.Note : '';
        this.othersIsLoading = false;
    }

    updateWarehouse() {
        if (this.name.nativeElement.text !== '') {
            this.store.dispatch(new CreateWarehouseUpdate(
                this.warehouse.ID, this.name.nativeElement.text, this.warehouse.ID_WarehouseType, this.warehouse.WarehouseType,
                this.warehouse.ID_Unit, this.warehouse.Unit, this.warehouse.RegistrationNumber, this.warehouse.UnitFullName,
                this.warehouse.ID_WarehouseMain, this.warehouse.WarehouseMain, this.street.nativeElement.text,
                this.city.nativeElement.text, this.postcode.nativeElement.text, this.note.nativeElement.text, this.warehouse.ID_Event,
                this.warehouse.ID_District, this.warehouse.GpsLatitude, this.warehouse.GpsLongitude, this.warehouse.ID_UnitCentral))
                .pipe(withLatestFrom(this.warehouseUpdate$))
                .subscribe(([_]) => {
                    feedbackMessage(FeedbackType.Success, 'Úprava skladu', `Sklad byl úspěšně upraven.`);
                    this.routerExtensions.back();
                }, err => {
                    console.log(err);
                    feedbackMessage(FeedbackType.Error, 'Úprava skladu', `Při úpravě skladu došlo k chybě. Zkontrolujte prosím zadané hodnoty.`);
                });

        } else {
            feedbackMessage(FeedbackType.Error, 'Úprava skladu', `Vyplňte jméno skladu.`);
            // this.routerExtensions.back();
        }
    }

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

    get saveIcon() {
        return String.fromCharCode(0xf0c7);
    }
}
