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 { action } 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 { PurchaseTypeAllOutput } from '../../entities/output/purchaseTypeAllOutput';
import { WarehouseAllOutput } from '../../entities/output/warehouseAllOutput';
import { WarehouseItemCategoryAllOutput } from '../../entities/output/warehouseItemCategoryAllOutput';
import { WarehouseItemInsertOutput } from '../../entities/output/warehouseItemInsertOutput';
import {
    CreateItemInsert,
    LoadPurchaseTypeAll,
    LoadWarehouseAll,
    LoadWarehouseItemCategoryAll
} from '../../state-mgmt/material-new.action';
import { MaterialNewState } from '../../state-mgmt/material-new.state';
import { feedbackMessage } from '../../utils/feedback-messages';
import { czechStringfromDate, dateFromCzechString } from '../../utils/myFunctions';

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

export class MaterialNewComponent implements OnInit {
    @ViewChild('name', {static: true}) name: ElementRef;
    @ViewChild('warehouse', {static: true}) warehouse: ElementRef;
    @ViewChild('category', {static: true}) category: ElementRef;
    @ViewChild('inventoryNumber', {static: true}) inventoryNumber: ElementRef;
    @ViewChild('description', {static: true}) description: ElementRef;
    @ViewChild('actualPrice', {static: true}) actualPrice: ElementRef;
    @ViewChild('note', {static: true}) note: ElementRef;
    @ViewChild('commercialRent', {static: true}) commercialRent: ElementRef;
    @ViewChild('unitRent', {static: true}) unitRent: ElementRef;
    @ViewChild('eventRent', {static: true}) eventRent: ElementRef;
    @ViewChild('rentPrice', {static: true}) rentPrice: ElementRef;
    @ViewChild('rentNote', {static: true}) rentNote: ElementRef;
    @ViewChild('purchaseType', {static: true}) purchaseType: ElementRef;
    @ViewChild('purchaseDate', {static: true}) purchaseDate: ElementRef;
    @ViewChild('purchaseNote', {static: true}) purchaseNote: ElementRef;
    @ViewChild('serialNumber', {static: true}) serialNumber: ElementRef;
    @ViewChild('accountNumber', {static: true}) accountNumber: ElementRef;
    @ViewChild('purchasePrice', {static: true}) purchasePrice: ElementRef;

    @Select(MaterialNewState.getWarehouses) warehouses$: Observable<WarehouseAllOutput[]>;
    @Select(MaterialNewState.getItemCategories) itemCategories$: Observable<WarehouseItemCategoryAllOutput[]>;
    @Select(MaterialNewState.getPurchaseTypes) purchaseTypes$: Observable<PurchaseTypeAllOutput[]>;
    @Select(MaterialNewState.getItemInsert) itemInsert$: Observable<WarehouseItemInsertOutput>;
    @Select(MaterialNewState.isLoading) isLoading$: Observable<boolean>;
    warehouses: WarehouseAllOutput[];
    itemCategories: WarehouseItemCategoryAllOutput[];
    purchaseTypes: PurchaseTypeAllOutput[];
    itemInsert: WarehouseItemInsertOutput;

    mainExpanded: boolean;
    rentExpanded: boolean;
    purchaseExpanded: boolean;
    canBeRent: boolean;
    othersIsLoading: boolean;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private routerExtensions: RouterExtensions,
        private store: Store,
        private modalService: ModalDialogService,
        private viewContainerRef: ViewContainerRef
    ) {
        this.mainExpanded = true;
        this.rentExpanded = false;
        this.purchaseExpanded = false;
        this.router.events.subscribe((val) => {
            if (val instanceof NavigationEnd) {
                if (this.router.url === '/material/materialNew') {
                    this.othersIsLoading = false;
                }
            }
        });
    }

    ngOnInit(): void {
        this.othersIsLoading = false;
        this.store.dispatch(new LoadWarehouseAll())
        .pipe(withLatestFrom(this.warehouses$))
        .subscribe(([_, warehouses]) => {
            this.warehouses = warehouses;

            if (warehouses.length > 0) {
                const w = this.warehouses.find(obj => +obj.ID === +this.route.snapshot.params['idWarehouse']);
                this.warehouse.nativeElement.text = w ? w.DisplayName : this.warehouses[0].DisplayName;

                this.store.dispatch(new LoadWarehouseItemCategoryAll())
                    .pipe(withLatestFrom(this.itemCategories$))
                    .subscribe(([_, categories]) => {
                        this.itemCategories = categories;
                        this.category.nativeElement.text = this.itemCategories[0].DisplayName;
                    }, err => {
                        feedbackMessage(FeedbackType.Error, 'Načtení categorií', 'Nepodařilo se načíst kategorie.');
                        console.log(err);
                    });
                this.store.dispatch(new LoadPurchaseTypeAll())
                    .pipe(withLatestFrom(this.purchaseTypes$))
                    .subscribe(([_, purchaseTypes]) => {
                        this.purchaseTypes = purchaseTypes;
                        this.purchaseType.nativeElement.text = this.purchaseTypes[0].DisplayName;
                    }, err => {
                        feedbackMessage(FeedbackType.Error, 'Načtení typů pořízení', 'Nepodařilo se načíst typy pořízení.');
                        console.log(err);
                    });
            }
        }, err => {
            feedbackMessage(FeedbackType.Error, 'Načtení skladů', 'Nepodařilo se načíst sklady.');
            console.log(err);
        });

        this.canBeRent = this.commercialRent.nativeElement.checked || this.unitRent.nativeElement.checked || this.eventRent.nativeElement.checked;

    }

    onRentExpandTap() {
        this.rentExpanded = !this.rentExpanded;
    }

    onMainExpandTap() {
        this.mainExpanded = !this.mainExpanded;
    }

    onPurchaseExpandTap() {
        this.purchaseExpanded = !this.purchaseExpanded;
    }

    switchClicked() {
        this.canBeRent = this.commercialRent.nativeElement.checked
            || this.unitRent.nativeElement.checked
        || this.eventRent.nativeElement.checked;
    }

    onTapWarehouseSelect(args: EventData) {
        const options = {
            message: 'Zvolte sklad',
            cancelButtonText: 'Zrušit',
            actions: this.warehouses.map(obj => obj.DisplayName)
        };

        action(options).then(async (result) => {
            (<TextField>args.object).text = this.warehouses.find(obj => obj.DisplayName === result).DisplayName;
        });
    }

    onTapCategorySelect(args: EventData) {
        const options = {
            message: 'Zvolte kategorii',
            cancelButtonText: 'Zrušit',
            actions: this.itemCategories.map(obj => obj.DisplayName)
        };

        action(options).then(async (result) => {
            (<TextField>args.object).text = this.itemCategories.find(obj => obj.DisplayName === result).DisplayName;
        });
    }

    onPurchaseTypeTap(args: EventData) {
        const options = {
            message: 'Zvolte způsob pořízení:',
            cancelButtonText: 'Zrušit',
            actions: this.purchaseTypes.map(obj => obj.DisplayName)
        };

        action(options).then(async (result) => {
            (<TextField>args.object).text = this.purchaseTypes.find(obj => obj.DisplayName === result).DisplayName;
        });
    }

    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);
                }
            });
    }

    createItem() {
        if (this.name.nativeElement.text !== '') {
            const purchDate = dateFromCzechString(this.purchaseDate.nativeElement.text);
            const purchType = this.purchaseTypes.find(obj => obj.DisplayName === this.purchaseType.nativeElement.text);
            console.log('jdu na to');
            this.store.dispatch(new CreateItemInsert(
                1,
                this.name.nativeElement.text,
                this.warehouses.find(obj => obj.DisplayName === this.warehouse.nativeElement.text).ID,
                this.itemCategories.find(obj => obj.DisplayName === this.category.nativeElement.text).ID,
                this.inventoryNumber.nativeElement.text,
                this.description.nativeElement.text,
                (purchDate ? purchDate.toISOString() : undefined),
                (purchType ? purchType.ID : undefined),
                this.purchaseNote.nativeElement.text,
                this.serialNumber.nativeElement.text,
                this.accountNumber.nativeElement.text,
                (this.purchasePrice.nativeElement.text !== '' ? this.purchasePrice.nativeElement.text : undefined),
                (this.actualPrice.nativeElement.text !== '' ? this.actualPrice.nativeElement.text : undefined),
                this.eventRent.nativeElement.checked,
                this.unitRent.nativeElement.checked,
                this.commercialRent.nativeElement.checked,
                (this.rentPrice.nativeElement.text !== '' ? this.rentPrice.nativeElement.text : undefined),
                this.rentNote.nativeElement.text,
                this.note.nativeElement.text))
                    .pipe(withLatestFrom(this.itemInsert$))
                    .subscribe(([_, insert]) => {
                        feedbackMessage(FeedbackType.Success, 'Přidání položky', `Položka byla úspěšně vytvořena.`);
                        this.routerExtensions.back();
                    }, err => {
                        console.log(err);
                        feedbackMessage(FeedbackType.Error, 'Přidání položky', `Při vytváření položky došlo k chybě. Zkontrolujte prosím zadané hodnoty.`);
                    });

        } else {
            feedbackMessage(FeedbackType.Error, 'Přidání položky', `Vyplňte jméno položky.`);
        }
    }

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

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

    get downIcon() {
        return String.fromCharCode(0xf107);
    }

    get rightIcon() {
        return String.fromCharCode(0xf105);
    }
}
