package com.lanyuanxiaoyao.leopard.server.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.leopard.core.entity.TaskTemplate;
import com.lanyuanxiaoyao.leopard.server.service.TaskTemplateService;
import com.lanyuanxiaoyao.service.template.controller.SimpleControllerSupport;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("task_template")
public class TaskTemplateController extends SimpleControllerSupport<TaskTemplate, TaskTemplateController.Item, TaskTemplateController.Item, TaskTemplateController.Item> {
  @Value("${spring.application.name}")
  private String application;

  public TaskTemplateController(TaskTemplateService service) {
    super(service);
  }

  @Override
  protected Function<Item, TaskTemplate> saveItemMapper() {
    return item -> {
      var template = new TaskTemplate();
      template.setId(item.id());
      template.setName(item.name());
      template.setDescription(item.description());
      template.setApplication(application);
      template.setChain(IdUtil.simpleUUID());
      template.setExpression(item.expression());
      template.setExpressionEl(StrUtil.format("CATCH(THEN(task_start, ({}), task_end)).DO(task_error)", item.expression()));
      return template;
    };
  }

  private Item convert(TaskTemplate template) {
    return new Item(
      template.getId(),
      template.getName(),
      template.getDescription(),
      template.getExpression()
    );
  }

  @Override
  protected Function<TaskTemplate, Item> listItemMapper() {
    return this::convert;
  }

  @Override
  protected Function<TaskTemplate, Item> detailItemMapper() {
    return this::convert;
  }

  public record Item(
    Long id,
    String name,
    String description,
    String expression
  ) {
  }
}
