package com.lanyuanxiaoyao.leopard.server.service;

import com.lanyuanxiaoyao.leopard.core.entity.TaskTemplate;
import com.lanyuanxiaoyao.leopard.core.repository.TaskTemplateRepository;
import com.lanyuanxiaoyao.service.template.service.SimpleServiceSupport;
import com.yomahub.liteflow.builder.el.LiteFlowChainELBuilder;
import com.yomahub.liteflow.meta.LiteflowMetaOperator;
import org.springframework.stereotype.Service;

@Service
public class TaskTemplateService extends SimpleServiceSupport<TaskTemplate> {
  public TaskTemplateService(TaskTemplateRepository repository) {
    super(repository);
  }

  private void validateExpression(String expression) {
    var response = LiteFlowChainELBuilder.validateWithEx(expression);
    if (!response.isSuccess()) {
      throw new RuntimeException(response.getCause());
    }
  }

  @Override
  public Long save(TaskTemplate entity) {
    validateExpression(entity.getExpression());
    Long id = super.save(entity);
    LiteflowMetaOperator.reloadAllChain();
    return id;
  }

  @Override
  public void save(Iterable<TaskTemplate> taskTemplates) {
    taskTemplates.forEach(template -> validateExpression(template.getExpression()));
    super.save(taskTemplates);
    LiteflowMetaOperator.reloadAllChain();
  }

  @Override
  public void remove(Iterable<Long> ids) {
    super.remove(ids);
    LiteflowMetaOperator.reloadAllChain();
  }

  @Override
  public void remove(Long id) {
    super.remove(id);
    LiteflowMetaOperator.reloadAllChain();
  }
}
