import AppConfig from '../appConfig.js';
import constants from '../constants.js';
import CSSClient from '../cssClient.js';
export default class ImageAccessDetailsRetriever {
    _APP_CONFIG_SCOPE_NAME = 'imageCredentials';
    imageId;
    imageName;
    constructor(imageName, imageId) {
        this.imageName = imageName;
        this.imageId = imageId;
    }
    async get(force = false) {
        const appConfig = await AppConfig.getInstance();
        if (!force) {
            const cachedCredentials = appConfig.getConfig(this.imageName, this._APP_CONFIG_SCOPE_NAME);
            if (cachedCredentials && (Date.now() < (cachedCredentials.expiresAt + constants.IMAGE_CREDENTIALS_EXPIRATION_GRACE_MS))) {
                return cachedCredentials;
            }
        }
        const cssClient = new CSSClient();
        let { imageId } = this;
        if (!imageId) {
            const images = await cssClient.get('/images', { name: this.imageName });
            if (!images || images.length === 0 || images[0].name !== this.imageName) {
                throw new Error(`Image with name "${this.imageName}" not found.`);
            }
            imageId = images[0].id;
        }
        const credentials = await cssClient.post(`/images/${imageId}/credentials`);
        const credentialsConfigValue = {
            expiresAt: Date.parse(credentials.expiresAt),
            imageUrl: credentials.imageUrl,
            password: credentials.password,
            readOnly: credentials.readOnly,
            username: credentials.username
        };
        appConfig.setConfig(this.imageName, credentialsConfigValue, this._APP_CONFIG_SCOPE_NAME);
        return credentialsConfigValue;
    }
    ;
}
