package com.bcxin.tenant.domain.entities;

import com.bcxin.Infrastructures.entities.EventEntityAbstract;
import com.bcxin.Infrastructures.entities.IAggregate;
import com.bcxin.Infrastructures.entities.OpEntityAbstract;
import com.bcxin.Infrastructures.enums.ProcessedStatus;
import com.bcxin.Infrastructures.enums.TrueFalseStatus;
import com.bcxin.tenant.domain.repositories.EventSubscribedActionLogRepository;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;

@Getter
@Setter(AccessLevel.PROTECTED)
@Table(name = "tenant_event_subscribers")
@Entity
public class EventSubscriberEntity extends OpEntityAbstract implements IAggregate {
    @Id
    private String id;

    @Column(name = "name", length = 200)
    private String name;


    /**
     * 处理器
     * 同步, 分发, 短信
     */
    @Column(name = "handler", length = 100)
    private String handler;

    /**
     * 选择器
     */
    @Column(name = "selector", length = 200)
    private String selector;

    /**
     * 最后一次处理的版本
     */
    @Column(name = "last_version")
    private Long lastVersion;

    /**
     * 上次处理的版本
     */
    @Column(name = "pre_version")
    private Long preVersion;

    @Column(name = "is_online", nullable = false)
    private TrueFalseStatus isOnline;

    /**
     * 处理状态
     */
    private ProcessedStatus status;

    @Transient
    public Long getFetchVersion() {
        return this.getLastVersion();
    }

    public void error(EventSubscribedActionLogRepository eventSubscribedActionLogRepository,EventEntityAbstract event, ProcessedStatus status, String message) {
        this.addActionLog(eventSubscribedActionLogRepository,event, status, message);
    }

    public void done(EventSubscribedActionLogRepository eventSubscribedActionLogRepository,EventEntityAbstract event, ProcessedStatus status, String message) {
        Long tmpVersion = this.getLastVersion();
        this.setLastVersion(event.getVersion());
        this.setPreVersion(tmpVersion);

        this.addActionLog(eventSubscribedActionLogRepository,event, status, message);
    }

    private void addActionLog(EventSubscribedActionLogRepository eventSubscribedActionLogRepository, EventEntityAbstract event, ProcessedStatus status, String message) {

        message = String.format("subscriber=%s; mapKey=%s; version=%s;:message=%s",
                this.getHandler(),
                event.getMapKey(),
                this.getLastVersion(),
                message);

        eventSubscribedActionLogRepository.save(
                EventSubscribedActionLogEntity.create(this, event.getId(),
                        event.getVersion(), status, message)
        );
    }

    @Override
    public String toString() {
        return String.format("subscriber;selector=%s;handler=%s", this.getSelector(), this.getHandler());
    }
}
