package com.example.demo.directions.api;

import java.util.List;
import java.util.Map;

import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

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

import jakarta.validation.Valid;

@Controller
@RequestMapping(DirectionsController.URL)
public class DirectionsController {
    public static final String URL = "/directions";
    private static final String DIRECTIONS_VIEW = "directions";
    private static final String DIRECTIONS_EDIT_VIEW = "direction-edit";
    private static final String DIRECTIONS_ATTRIBUTE = "directions";
    private static final String DEPARTMENT_ATTRIBUTE = "departments";
    private static final String PAGE_ATTRIBUTE = "page";
    private final DirectionsService directionsService;
    private final ModelMapper modelMapper;
    private final DepartmentService departmentService;

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

    private DirectionsDto toDto(DirectionsEntity entity) {
        return modelMapper.map(entity, DirectionsDto.class);
    }

    private DirectionsEntity toEntity(DirectionsDto dto) {
        final DirectionsEntity entity = modelMapper.map(dto, DirectionsEntity.class);
        entity.setDepartment(departmentService.get(dto.getDepartmentId()));
        return entity;
    }

    private DirectionsGroupedDto toGroupedDto(DirectionsGrouped entity){
        return modelMapper.map(entity, DirectionsGroupedDto.class);
    }

    private List<DepartmentDto> getDepartments(){
       return modelMapper.map(departmentService.getAll(), new TypeToken<List<DepartmentDto>>(){}.getType());
    }
    
    @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;
    }
    
    @GetMapping("/edit/")
    public String create(Model model,
            @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page) {
        model.addAttribute(DIRECTIONS_ATTRIBUTE, new DirectionsDto());
        model.addAttribute(DEPARTMENT_ATTRIBUTE, getDepartments());
        model.addAttribute(PAGE_ATTRIBUTE, page);
        return DIRECTIONS_EDIT_VIEW;
    }

    @PostMapping("/edit/")
    public String create(
            @ModelAttribute(name = DIRECTIONS_ATTRIBUTE) @Valid DirectionsDto direction,
            @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
            BindingResult bindingResult,
            Model model,
            RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            model.addAttribute(PAGE_ATTRIBUTE, page);
            return DIRECTIONS_EDIT_VIEW;
        }
        redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
        directionsService.create(toEntity(direction));
        return Constants.REDIRECT_VIEW + URL;
    }

    @GetMapping("/edit/{id}")
    public String update(
            @PathVariable(name = "id") Long id,
            @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
            Model model) {
        if (id <= 0) {
            throw new IllegalArgumentException();
        }
        model.addAttribute(DIRECTIONS_ATTRIBUTE, toDto(directionsService.get(id)));
        model.addAttribute(DEPARTMENT_ATTRIBUTE, getDepartments());
        model.addAttribute(PAGE_ATTRIBUTE, page);
        return DIRECTIONS_EDIT_VIEW;
    }

    @PostMapping("/edit/{id}")
    public String update(
            @PathVariable(name = "id") Long id,
            @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
            @ModelAttribute(name = DIRECTIONS_ATTRIBUTE) @Valid DirectionsDto direction,
            BindingResult bindingResult,
            Model model,
            RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return DIRECTIONS_EDIT_VIEW;
        }
        if (id <= 0) {
            throw new IllegalArgumentException();
        }
        redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
        directionsService.update(id, toEntity(direction));
        return Constants.REDIRECT_VIEW + URL;
    }

    @PostMapping("/delete/{id}")
    public String delete(
            @PathVariable(name = "id") Long id,
            @RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
            RedirectAttributes redirectAttributes) {
        redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
        directionsService.delete(id);
        return Constants.REDIRECT_VIEW + URL;
    }
}
