import { Injectable } from "@angular/core";
import { APP_ID, wsDocumentStorage, wsOrganizationUnit } from '~/constants/api.constants';
import { USER_TOKEN } from '~/constants/login-constants';
import { WebApiService } from '~/core/services/web-api.service';
import { PersonPhoto } from '~/pages/search-person/entities/input/personPhoto';
import { PersonPhotoOutput } from '~/pages/search-person/entities/output/personPhotoOutput';
import { ApplicationSettings as AppSettings, ImageSource } from '@nativescript/core';

import { DocumentDetailData } from "~/pages/material/entities/input/documentDetailData";
import { DocumentDetailDataOutput } from "~/pages/material/entities/output/documentDetailDataOutput";


@Injectable()
export class ImageService {

    promises: { [key: number]: Promise<ImageSource> } = {}
    images: { [key: string]: ImageSource } = {}
    eventLogoPromises: { [key: number]: Promise<ImageSource> } = {}
    logos: { [key: string]: ImageSource } = {}

    constructor(private webApiService: WebApiService,
    ) {
    }


    loadEduEventLogo(logoId: number): Promise<ImageSource> {
        if (logoId in this.logos) {
            return Promise.resolve(this.logos[logoId])
        }
        const usrToken = AppSettings.getString(USER_TOKEN)
        if (logoId in this.eventLogoPromises) {
            return this.eventLogoPromises[logoId]
        }
        const p = this.webApiService.call(
            new DocumentDetailData(APP_ID, usrToken, logoId),
            () => new DocumentDetailDataOutput(),
            wsDocumentStorage
        ).toPromise().then((res: string) => {
            if (res) {
                this.logos[logoId] = ImageSource.fromBase64Sync(res)
                return this.logos[logoId]
            }
            return null;
        }).catch(e => {
            throw e;
        })

        this.eventLogoPromises[logoId] = p;
        return p;
    }

    loadPersonPhoto(personId: number): Promise<ImageSource> {
        if (personId in this.images) {
            return Promise.resolve(this.images[personId])
        }
        const usrToken = AppSettings.getString(USER_TOKEN)
        if (personId in this.promises) {
            return this.promises[personId]
        }
        const p = this.webApiService.call(
            new PersonPhoto(APP_ID, usrToken, personId, 'small'),
            () => new PersonPhotoOutput(),
            wsOrganizationUnit
        ).toPromise().then((res: PersonPhotoOutput[]) => {
            if (res.length === 1) {
                const photo = res[0];
                if (photo.PhotoContent) {
                    this.images[personId] = ImageSource.fromBase64Sync(photo.PhotoContent)
                    return this.images[personId]
                }
            }
            return null;
        })

        this.promises[personId] = p;
        return p;
    }

}