package com.collabnet.ctf.events.custom.events;

import com.collabnet.ce.soap60.webservices.tracker.ArtifactSoapDO;
import com.collabnet.ctf.events.Synchronous;
import com.collabnet.ctf.events.EventContext;
import com.collabnet.ctf.events.EventListener;
import com.collabnet.ctf.events.SoapVersion;

@EventListener(version = SoapVersion.SOAP_60)
public class ClosedArtifactValidator {

    private static final String ERROR_CLOSED_ARTIFACT_UPDATE = "You can not update a closed artifact. " +
            "Please re-open the artifact to proceed with update";

    @Synchronous(topic = {"object.item.Artifact.update"})
    public void validate(final EventContext context) throws Exception {
        ArtifactSoapDO originalArtf = (ArtifactSoapDO) context.getOriginalData();
        ArtifactSoapDO updatedArtf = (ArtifactSoapDO) context.getUpdatedData();

        // If the artifact is in `Closed` meta-status then dont allow
        // the update.

        if (originalArtf.getStatusClass().equals("Close") &&
                updatedArtf.getStatusClass().equals("Close")) {

            // Pass an error message for UI. This will be shown on UI
            context.addErrorMessage(ERROR_CLOSED_ARTIFACT_UPDATE);

            // Fail the artifact update
            throw new Exception(ERROR_CLOSED_ARTIFACT_UPDATE);
        }
    }
}
