import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';

import { ActivatedRoute } from '@angular/router';
import { WebApiService } from '~/core/services/web-api.service';
import { DocumentDetailData } from '~/pages/material/entities/input/documentDetailData';
import { DocumentDetailDataOutput } from '~/pages/material/entities/output/documentDetailDataOutput';
import { USER_TOKEN } from '~/constants/login-constants';
import { APP_ID, wsDocumentStorage } from '~/constants/api.constants';
import { Image as ImageEl } from '@nativescript/core/ui/image'
import { screen } from "nativescript-platform"
import { Subscription } from 'rxjs';
import { ApplicationSettings, ImageSource } from '@nativescript/core';
import { RouterExtensions } from '@nativescript/angular';


@Component({
    selector: 'EduEventImageView',
    moduleId: module.id,
    templateUrl: './edu-event-image-view.component.html',
    styleUrls: ['./_edu-event-image-view.component.scss']
})
export class EduEventImageViewComponent implements OnInit, OnDestroy {
    imageId: number;

    imageSource: ImageSource;
    imageTitle: string;
    sub: Subscription;
    @ViewChild('imageEl', { static: true })
    imageEl: ElementRef;

    minScale = screen.width
    currentScale = this.minScale
    maxScale = screen.height * 1.5

    constructor(
        private routerExtensions: RouterExtensions,
        private route: ActivatedRoute,
        private webApiService: WebApiService

    ) {
    }
    ngOnDestroy(): void {
        if (this.sub) {
            this.sub.unsubscribe();
        }
    }

    ngOnInit(): void {
        this.route.params.subscribe((params) => {
            this.imageId = parseInt(params['id'], 10);
            this.imageTitle = params['title'];
            const img = this.imageEl.nativeElement as ImageEl
            img.on('doubleTap', (args) => {
                this.currentScale = this.currentScale === this.minScale ? this.maxScale : this.minScale;
                img.width = this.currentScale;
            })

            this.sub = this.webApiService.call(
                new DocumentDetailData(APP_ID, ApplicationSettings.getString(USER_TOKEN), this.imageId),
                () => new DocumentDetailDataOutput(),
                wsDocumentStorage
            ).subscribe(async (res: string) => {
                this.imageSource = await ImageSource.fromBase64(res);
            }, err => {
                console.log(err)
            })
        });
    }
    onBackButton(): void {
        this.routerExtensions.back();
    }
}
