package com.ecep.contract.vm;

import java.util.Objects;

import com.ecep.contract.model.IdentityEntity;
import com.ecep.contract.service.ViewModelService;

import javafx.beans.property.SimpleIntegerProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class IdentityViewModel<T extends IdentityEntity> extends BaseViewModel<T> {
    /**
     * 主键Id
     */
    private SimpleIntegerProperty id = new SimpleIntegerProperty();

    @Override
    protected void updateFrom(T v) {
        super.updateFrom(v);
        if (v.getId() != null) {
            id.set(v.getId());
        }
    }

    @Override
    public boolean copyTo(T v) {
        boolean changed = super.copyTo(v);
        if (!Objects.equals(id.get(), v.getId())) {
            v.setId(id.get());
            changed = true;
        }
        return changed;
    }

    public <TV extends IdentityViewModel<T>> void saveInFxApplicationThread(ViewModelService<T, TV> service) {
        T cloudRk = service.findById(getId().get());
        if (copyTo(cloudRk)) {
            T saved = service.save(cloudRk);
            updateInFxApplicationThread(saved, this);
        }
    }
}
