package com.utopiaindustries.controller;

import com.utopiaindustries.service.ProcessService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping( "/processes" )
public class ProcessController {

    private final ProcessService processService;

    public ProcessController(ProcessService processService) {
        this.processService = processService;
    }

    @GetMapping
    public String showProcesses( Model model ){
        model.addAttribute("processes", processService.findAllProcesses() );
        return "process-list";
    }

    @GetMapping("/edit" )
    public String editProcesses(Model model ){
        model.addAttribute("processWrapper", processService.getAllProcessWrapper() );
        return "_process-fragment";
    }

    @PostMapping( "/edit" )
    public String saveProcesses(@ModelAttribute ProcessListWrapper processWrapper,
                                RedirectAttributes redirectAttributes ){
        try {
            processService.saveAll( processWrapper );
            redirectAttributes.addFlashAttribute("success", "Process saved");
        } catch ( Exception e ){
            redirectAttributes.addFlashAttribute("error", e.getMessage() );
        }
        return "redirect:/processes";
    }
}
