package com.iqser.red.service.persistence.service.v1.api.shared.model.annotations;

import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.Objects;

import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.entitylog.Change;
import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.entitylog.ChangeType;
import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.entitylog.PropertyChange;
import com.iqser.red.service.persistence.service.v1.api.shared.model.utils.ChangeUtils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@UtilityClass
@Slf4j
public class ChangeFactory {

    public Change toChange(ChangeType changeType, OffsetDateTime offsetDateTime, int analysisNumber, PropertyChange... propertyChanges) {

        Change change = new Change();
        change.setDateTime(offsetDateTime);
        change.setAnalysisNumber(analysisNumber);
        change.setType(changeType);

        addPropertyChanges(change, propertyChanges);

        return change;
    }


    public void addPropertyChanges(Change change, PropertyChange... propertyChanges) {

        Arrays.stream(propertyChanges)
                .forEach(propertyChange -> {
                    if (!Objects.equals(propertyChange.getOldValue(), propertyChange.getNewValue())
                        && !propertyChange.getProperty().equals("manualChanges")
                        && !propertyChange.getProperty().equals("changes")) {
                        change.addChange(propertyChange.getProperty(), ChangeUtils.buildVisualChange(propertyChange.getOldValue(), propertyChange.getNewValue()));
                    }
                });
    }

}
