package dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf.creators

import dev.fyloz.trial.colorrecipesexplorer.exception.SimdutException
import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityAlreadyExistsException
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseCode
import dev.fyloz.trial.colorrecipesexplorer.model.Material
import dev.fyloz.trial.colorrecipesexplorer.model.MaterialSaveDto
import dev.fyloz.trial.colorrecipesexplorer.service.model.MaterialJavaService
import dev.fyloz.trial.colorrecipesexplorer.service.model.MaterialTypeJavaService
import dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.CREATOR_MATERIAL
import dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf.message
import dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf.modelAndView
import org.springframework.context.annotation.Profile
import org.springframework.http.MediaType
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.ModelAndView
import javax.validation.Valid

@Controller
@Profile("thymeleaf")
class MaterialCreatorController(val materialService: MaterialJavaService, val materialTypeService: MaterialTypeJavaService) {
    @GetMapping(CREATOR_MATERIAL)
    fun getPage(model: ModelAndView, @RequestParam(required = false) material: Material? = null): ModelAndView {
        return modelAndView(model) {
            viewName = CREATOR_MATERIAL
            addObject("material", material ?: Material())
            addObject("materialTypes", materialTypeService.all)
        }
    }

    @PostMapping(value = [CREATOR_MATERIAL], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    fun createMaterial(@Valid material: Material, simdut: MultipartFile): ModelAndView {
        return getPage(modelAndView {
            try {
                materialService.save(MaterialSaveDto(material.name, material.inventoryQuantity, material.materialType!!, simdut))
                message(ResponseCode.SUCCESS_SAVING_MATERIAL, material.name)
            } catch (ex: EntityAlreadyExistsException) {
                message(ResponseCode.MATERIAL_ALREADY_EXIST, material.name)
            } catch (ex: SimdutException) {
                message(ResponseCode.SUCCESS_SAVING_MATERIAL, material.name)
                message(ResponseCode.ERROR_SAVING_SIMDUT)
            }
        })
    }
}
