package com.example.demo.directions.api;

import java.util.Map;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.directions.model.DirectionsGrouped;
import com.example.demo.directions.service.DirectionsService;

@Controller
@RequestMapping(DirectionsController.URL)
public class DirectionsController {
    public static final String URL = "/directions";
    private static final String DIRECTIONS_VIEW = "directions";
    private static final String PAGE_ATTRIBUTE = "page";
    private final DirectionsService directionsService;
    private final ModelMapper modelMapper;

    public DirectionsController(DirectionsService directionsService, ModelMapper modelMapper) {
        this.directionsService = directionsService;
        this.modelMapper = modelMapper;
    }

    private DirectionsGroupedDto toGroupedDto(DirectionsGrouped entity){
        return modelMapper.map(entity, DirectionsGroupedDto.class);
    }
    
    @GetMapping
    public String getAllWithDepartment(
            @RequestParam(name=PAGE_ATTRIBUTE, defaultValue = "0") int page,
            @RequestParam(name="reset", required = false, defaultValue = "false") String reset,
            Model model,
            String name) {
                if (reset.contains("true")){
                    name = "";
                }
        final Map<String, Object> attributes = PageAttributesMapper.
            toAttributes(directionsService.getAllWithDepartment(page, Constants.DEFAULT_PAGE_SIZE, name), this::toGroupedDto);
        model.addAllAttributes(attributes);
        model.addAttribute(PAGE_ATTRIBUTE, page);
        model.addAttribute("name", name);
        return DIRECTIONS_VIEW;
    }
}
