import { AbstractRepository } from '@crosslab/service-common';
import { WEEK } from '../../../globals.js';
import { calculateAvailability } from '../../../methods/availability.js';
import { deviceUrlFromId } from '../../../methods/urlFromId.js';
import { connectedDevices } from '../../../operations/devices/websocket/handling/index.js';
import { ConcreteDeviceModel } from '../../model.js';
export class ConcreteDeviceRepository extends AbstractRepository {
    dependencies = {};
    constructor() {
        super('Concrete Device');
    }
    dependenciesMet() {
        if (!this.dependencies.deviceOverview)
            return false;
        return true;
    }
    initialize(entityManager) {
        this.repository = entityManager.getRepository(ConcreteDeviceModel);
    }
    async create(data) {
        const model = await super.create(data);
        model.type = 'device';
        model.availabilityRules = [];
        model.services ??= [];
        return model;
    }
    async write(model, data) {
        if (!this.isInitialized())
            this.throwUninitializedRepositoryError();
        const { type: _type, description: _description, experiment, isPublic: _isPublic, name: _name, owner: _owner, services, viewer: _viewer, ...additionalAttributes } = { ...model.additionalAttributes, ...data };
        await this.dependencies.deviceOverview.write(model, data);
        if (experiment)
            model.experiment = experiment;
        if (services)
            model.services = services;
        model.additionalAttributes = additionalAttributes;
    }
    async format(model) {
        if (!this.isInitialized())
            this.throwUninitializedRepositoryError();
        return {
            ...model.additionalAttributes,
            ...(await this.dependencies.deviceOverview.format(model)),
            type: 'device',
            connected: connectedDevices.has(model.uuid),
            announcedAvailability: calculateAvailability(model.availabilityRules, Date.now(), Date.now() + WEEK),
            experiment: model.experiment ?? undefined,
            services: model.services,
            instanceOf: model.instanceOf?.uuid
                ? deviceUrlFromId(model.instanceOf?.uuid)
                : undefined,
        };
    }
}
//# sourceMappingURL=concreteDevice.js.map