package com.huigou.data.domain.listener;

import com.huigou.data.repository.GeneralRepositorySuper;
import com.huigou.domain.IdentifiedEntity;
import com.huigou.util.ApplicationContextWrapper;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.util.ReflectionUtils;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.lang.reflect.Field;

@Configurable
public class VersionListener {

    @Deprecated
    public final static String GET_NEXT_SEQ_SQL = "SELECT version_seq.nextval from DUAL";
    private final static String VERSION_FIELD_NAME = "version";

    private Long getNextId() {
        GeneralRepositorySuper generalRepository = ApplicationContextWrapper.getBean(GeneralRepositorySuper.class);
        return generalRepository.getVersionNextId();
    }

    @PrePersist
    public void beforeCreate(Object target) {
        updateVersion(target);
    }

    @PreUpdate
    public void beforeUpdate(Object target) {
        updateVersion(target);
    }

    private void updateVersion(Object target) {
        if (target instanceof IdentifiedEntity) {
            ((IdentifiedEntity) target).setVersion(getNextId());
        } else {
            Field field = ReflectionUtils.findField(target.getClass(), VERSION_FIELD_NAME);
            if (field != null) {
                field.setAccessible(true);
                ReflectionUtils.setField(field, target, getNextId());
            }
        }
    }

}
