package p.packer.services;

import p.packer.events.PackerEvent;
import p.packer.events.PackerEventKind;
import p.packer.events.PackerEventSink;
import p.packer.events.PackerProgress;
import p.packer.messages.PackerProjectContext;

import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

public final class PackerOperationEventEmitter {
    private final PackerProjectContext project;
    private final PackerEventSink sink;
    private final String operationId;
    private long sequence;

    public PackerOperationEventEmitter(PackerProjectContext project, PackerEventSink sink) {
        this(project, sink, UUID.randomUUID().toString());
    }

    public PackerOperationEventEmitter(PackerProjectContext project, PackerEventSink sink, String operationId) {
        this.project = Objects.requireNonNull(project, "project");
        this.sink = Objects.requireNonNull(sink, "sink");
        this.operationId = Objects.requireNonNull(operationId, "operationId").trim();
    }

    public String operationId() {
        return operationId;
    }

    public void emit(PackerEventKind kind, String summary, List<String> affectedAssets) {
        emit(kind, summary, null, affectedAssets);
    }

    public void emit(PackerEventKind kind, String summary, PackerProgress progress, List<String> affectedAssets) {
        sink.publish(new PackerEvent(
                project.projectId(),
                operationId,
                sequence++,
                Objects.requireNonNull(kind, "kind"),
                Instant.now(),
                Objects.requireNonNull(summary, "summary"),
                progress,
                affectedAssets == null ? List.of() : List.copyOf(affectedAssets)));
    }
}
