package com.atlassian.stash.internal.scm.git.bulk;

import com.atlassian.bitbucket.scm.bulk.BulkChangeType;
import com.atlassian.stash.internal.scm.git.io.NullTerminatedReader;
import com.atlassian.stash.internal.scm.git.io.NullTerminatedWriter;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;

public class FileChange {

    private final String path;
    private final BulkChangeType changeType;
    private final String contentId;

    FileChange(String path, BulkChangeType changeType, String contentId) {
        this.path = path;
        this.changeType = changeType;
        this.contentId = contentId;
    }

    @Nonnull
    public String getPath() {
        return path;
    }

    @Nonnull
    public BulkChangeType getChangeType() {
        return changeType;
    }

    @Nonnull
    public String getContentId() {
        return contentId;
    }

    @Nullable
    static FileChange read(NullTerminatedReader reader) throws IOException {
        String path = reader.readSegment();
        if (path == null) {
            return null;
        }
        String changeTypeString = reader.readSegment();
        if (changeTypeString == null) {
            return null;
        }
        BulkChangeType changeType = BulkChangeType.valueOf(changeTypeString);
        String contentId = reader.readSegment();
        if (contentId == null) {
            return null;
        }
        return new FileChange(path, changeType, contentId);
    }

    static void write(String path, BulkChangeType changeType, String contentId, NullTerminatedWriter writer) throws IOException {
        writer.writeSegment(path);
        writer.writeSegment(changeType.name());
        writer.writeSegment(contentId);
    }
}
