package com.utopiaindustries.controller;

import com.utopiaindustries.model.Roles;
import com.utopiaindustries.model.ctp.User;
import com.utopiaindustries.service.InventoryAccountService;
import com.utopiaindustries.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping( "/users" )
public class UserController {

    private final UserService userService;
    private final InventoryAccountService inventoryAccountService;

    public UserController(UserService userService, InventoryAccountService inventoryAccountService) {
        this.userService = userService;
        this.inventoryAccountService = inventoryAccountService;
    }

    @GetMapping
    public String getAllUsers( Model model ){
        model.addAttribute( "users", userService.findAllUsers() );
        return "users";
    }


    @GetMapping( "/new" )
    public String addUserForm( Model model ){
        model.addAttribute("user", userService.createEmptyUser() );
        model.addAttribute("accounts", inventoryAccountService.findInventoryAccounts() );
        model.addAttribute("roles", Roles.values() );
        model.addAttribute("isNew", false );
        return "_user-fragment";
    }

    @GetMapping( "/edit/{username}" )
    public String addUserForm(Model model, @PathVariable String username ){
        model.addAttribute("user", userService.getUser( username ) );
        model.addAttribute("accounts", inventoryAccountService.findInventoryAccounts() );
        model.addAttribute("roles", Roles.values() );
        model.addAttribute("isNew", true );
        return "_user-fragment";
    }

    @PostMapping( "/edit" )
    public String saveUser( Model model,
                            @ModelAttribute User user ,
                            RedirectAttributes redirectAttributes ){
        try {
            userService.saveUser( user, true );
            redirectAttributes.addFlashAttribute("success", "User Successfully Saved!" );
        } catch ( Exception e ){
            redirectAttributes.addFlashAttribute("error", e.getMessage() );
        }
        return "redirect:/users/new";
    }

    @PostMapping( "/edit/{username}" )
    public String saveUser( @PathVariable String username,
                            @ModelAttribute User user,
                            RedirectAttributes redirectAttributes ){
        try {
            userService.saveUser( user, false );
            redirectAttributes.addFlashAttribute("success", "User Successfully Edited!" );
        } catch ( Exception e ){
            redirectAttributes.addFlashAttribute("error", e.getMessage() );
        }
        return "redirect:/users";
    }

}
