package com.ecep.contract.vm;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Objects;

import com.ecep.contract.model.CloudTyc;
import com.ecep.contract.model.Company;
import com.ecep.contract.util.MyDateTimePropertyUtils;

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

@Data
@EqualsAndHashCode(callSuper = false)
public class CloudTycInfoViewModel extends IdentityViewModel<CloudTyc> {
    /**
     * 云端Id
     */
    private SimpleStringProperty cloudId = new SimpleStringProperty();
    /**
     * 公司
     */
    private SimpleObjectProperty<Company> company = new SimpleObjectProperty<>();
    /**
     * 最后更新日期
     */
    private SimpleObjectProperty<LocalDateTime> latest = new SimpleObjectProperty<>();
    /**
     * Version
     */
    private SimpleIntegerProperty version = new SimpleIntegerProperty();
    private SimpleIntegerProperty score = new SimpleIntegerProperty();
    private SimpleObjectProperty<LocalDateTime> cloudLatest = new SimpleObjectProperty<>();

    @Override
    protected void updateFrom(CloudTyc info) {
        super.updateFrom(info);
        update_((CloudTyc) info);
    }

    private void update_(CloudTyc info) {
        score.set(info.getScore());

        if (info.getCloudLatest() != null) {
            ZoneId zone = ZoneId.systemDefault();
            ZonedDateTime zonedDateTime = info.getCloudLatest().atZone(zone);
            LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
            cloudLatest.set(localDateTime);
        } else {
            cloudLatest.set(null);
        }
    }

    @Override
    public boolean copyTo(CloudTyc info) {
        boolean modified = super.copyTo(info);
        if (copyTo_((CloudTyc) info)) {
            modified = true;
        }
        return modified;
    }

    private boolean copyTo_(CloudTyc info) {
        boolean modified = super.copyTo(info);
        if (!Objects.equals(info.getId(), getId().get())) {
            info.setId(getId().get());
            modified = true;
        }

        if (!Objects.equals(info.getScore(), getScore().get())) {
            info.setScore(getScore().get());
            modified = true;
        }

        Instant latest = MyDateTimePropertyUtils.localDateTimeToInstant(cloudLatest);
        if (!Objects.equals(info.getCloudLatest(), latest)) {
            info.setCloudLatest(latest);
            modified = true;
        }

        return modified;
    }

    public static CloudTycInfoViewModel from(CloudTyc cc) {
        CloudTycInfoViewModel model = new CloudTycInfoViewModel();
        model.update(cc);
        return model;
    }
}
