package com.bytesw.bytebot.controller;

import com.bytesw.bytebot.bean.SchedulerTaskBean;
import com.bytesw.bytebot.service.SchedulerTaskService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController()
@RequestMapping("/service/settings/scheduler-task")
@ProgramSecurity("SCHEDULER-TASK")
@Log4j2
public class SchedulerTaskController extends XDFController<SchedulerTaskBean, BigInteger> {
    public SchedulerTaskController(SchedulerTaskService service) {
        super(service);
    }

    @ApiResponses({@ApiResponse(
            code = 200,
            message = "Success",
            response = ResponseEntity.class
    ), @ApiResponse(
            code = 505,
            message = "Internal Server Error"
    )})
    @RequestMapping(
            method = {RequestMethod.POST},
            value = {"/page"}
    )
    @ResponseBody
    @Override
    @PreAuthorize("hasPermission(this, 'view')")
    public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<SchedulerTaskBean> pagination) {
        if (!Objects.isNull(pagination.getFilterExpression()) && !pagination.getFilterExpression().isEmpty()) {
            String filterExpression = pagination.getFilterExpression();
            if (filterExpression.contains("(internals==Y)")) {
                filterExpression = filterExpression.replace("(internals==Y)", "(internals==true)");
            }
            if (filterExpression.contains("calendarName")) {
                filterExpression = filterExpression.replace("calendarName", "calendar.name");
            }
            pagination.setFilterExpression(filterExpression);
        }
        this.service.searchByPagination(pagination);
        return new ResponseEntity(this.gson.toJson(pagination), HttpStatus.OK);
    }

    @ApiResponses({@ApiResponse(
            code = 200,
            message = "Success",
            response = ResponseEntity.class
    ), @ApiResponse(
            code = 505,
            message = "Internal Server Error"
    )})
    @RequestMapping(
            method = {RequestMethod.GET},
            value = {"/initial-data"}
    )
    @ResponseBody
    @PreAuthorize("hasPermission(this, 'view')")
    public ResponseEntity<String> getInitialData() {
        Map<String, List> initialData = ((SchedulerTaskService) this.service).getInitialData();
        return new ResponseEntity(this.gson.toJson(initialData), HttpStatus.OK);
    }
}
