import { Component, ElementRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { ModalDialogOptions, ModalDialogService, RouterExtensions } from '@nativescript/angular';
import { EventData, TextField } from '@nativescript/core';
import { confirm } from '@nativescript/core/ui/dialogs';
import { Select, Store } from '@ngxs/store';
import { FeedbackType } from 'nativescript-feedback';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { ModalDatePickerComponent } from '../../components/modal-view-date-picker/modal-view-date-picker.component';
import { WarehouseItemUpdateDeleteOutput } from '../../entities/output/warehouseItemUpdateDeleteOutput';
import { CreateMaterialDelete } from '../../state-mgmt/material-delete.action';
import { MaterialDeleteState } from '../../state-mgmt/material-delete.state';
import { feedbackMessage } from '../../utils/feedback-messages';
import { czechStringfromDate, dateFromCzechString } from '../../utils/myFunctions';

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

export class MaterialDeleteComponent implements OnInit {
    @ViewChild('name', {static: true}) name: ElementRef;
    @ViewChild('date', {static: true}) date: ElementRef;
    @ViewChild('note', {static: true}) note: ElementRef;

    @Select(MaterialDeleteState.getItemDelete) itemDelete$: Observable<WarehouseItemUpdateDeleteOutput>;
    @Select(MaterialDeleteState.isLoading) isLoading$: Observable<boolean>;
    othersIsLoading: boolean;
    itemName: string;
    itemId: number;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private modalService: ModalDialogService,
        private viewContainerRef: ViewContainerRef
    ) {
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (RegExp('\/material\/materialDelete\/[^/]+').test(this.router.url)) {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    onLoad() {
        this.othersIsLoading = false;

    }

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.itemId = +(this.route.snapshot.params['id']);
        this.itemName = this.route.snapshot.params['name'];
        this.date.nativeElement.text = czechStringfromDate(new Date());
    }

    deleteItem() {
        const options = {
            title: 'Vyřazení položky',
            message: 'Opravdu chcete tuto položku vyřadit? Její vrácení je možné pouze přes webové rozhraní.',
            okButtonText: 'Ano',
            cancelButtonText: 'Ne'
        };
        confirm(options).then((result: boolean) => {
            if (result) {
                const date = dateFromCzechString(this.date.nativeElement.text);
                this.store.dispatch(new CreateMaterialDelete(
                    [this.itemId],
                    (date ? date.toISOString() : undefined),
                    this.note.nativeElement.text))
                    .pipe(withLatestFrom(this.itemDelete$))
                    .subscribe(([_, update]) => {
                        feedbackMessage(FeedbackType.Success, 'Vyřazení položky', `Položka byla úspěšně vyřazena.`);
                        this.routerExtensions.back();
                    }, err => {
                        feedbackMessage(FeedbackType.Error, 'Vyřazení položky', 'Nepodařilo se vyřadit položku.');
                        console.log(err);
                    });
            }
        });

    }

    /**
     * opens modal view for choosing date
     * @param args textField with date
     */
    showDate(args: EventData) {
        this.othersIsLoading = true;
        const txtField = <TextField>args.object;
        const date = txtField.text.split('.');
        const options: ModalDialogOptions = {
            viewContainerRef: this.viewContainerRef,
            context: {
                day: date.length === 3 ? date[0].trim() : new Date().getDate(),
                month: date.length === 3 ? date[1].trim() : new Date().getMonth() + 1,
                year: date.length === 3 ? date[2].trim() : new Date().getFullYear(),
                minDate: null
            },
            fullscreen: false
        };
        this.othersIsLoading = false;
        this.modalService.showModal(ModalDatePickerComponent, options)
            .then((result: Date) => {
                if (result) {
                    txtField.text = czechStringfromDate(result);
                }
            });
    }

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

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

}
