import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { screen } from "nativescript-platform"
import { WebViewExt } from '@nota/nativescript-webview-ext';
import { mapHtml } from './map';
import { jsStr } from './mapscript';
import { ModalDialogParams } from '@nativescript/angular';
import { Observable } from 'rxjs';
import { Select, Store } from '@ngxs/store';
import { GenEventMapPickerState, SetIsLoading } from '~/pages/event/state-mgmt/gen/gen-event-map-picker.state';

@Component({
    selector: 'MapPickerModal',
    moduleId: module.id,
    templateUrl: './map-picker-modal.component.html',
    // styleUrls: ['./_map-picker-modal.component.scss'],

})
export class MapPickerModal implements OnInit, AfterViewInit {
    @ViewChild('mapView', { static: true })
    webview: ElementRef<WebViewExt>;
    @Select(GenEventMapPickerState.isLoading)
    isLoading$: Observable<boolean>;

    htmlstr = ''
    constructor(
        private params: ModalDialogParams,
        private store: Store,
    ) {
    }

    ngOnInit(): void {

        this.store.dispatch(new SetIsLoading(true));
        this.htmlstr = mapHtml(screen.width, screen.height - 225, jsStr);
    }

    onSave() {
        const isLoading = this.store.selectSnapshot(GenEventMapPickerState.isLoading)
        if (!isLoading) {
            const webview = this.webview && this.webview.nativeElement;
            webview.executePromise('$map.locationData').then(res => {
                this.params.closeCallback(res);
            })
        }
    }
    ngAfterViewInit(): void {
        const webview = this.webview && this.webview.nativeElement;
        webview.on(WebViewExt.loadFinishedEvent, () => {
            if (this.params.context.lat && this.params.context.long) {
                const { lat, long } = this.params.context
                webview.executeJavaScript(`$map.moveMarker(${parseFloat(long)}, ${parseFloat(lat)})`)
            }
            this.store.dispatch(new SetIsLoading(false));
        });
    }

    close() {
        this.params.closeCallback();
    }
}
