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

import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityAlreadyExistsException;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ModelResponseBuilder;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseCode;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseDataType;
import dev.fyloz.trial.colorrecipesexplorer.model.Company;
import dev.fyloz.trial.colorrecipesexplorer.service.model.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.CREATOR_COMPANY;

@Controller
@Profile("thymeleaf")
public class CompanyCreatorController {

    private CompanyService companyService;

    @Autowired
    public CompanyCreatorController(CompanyService companyService) {
        this.companyService = companyService;
    }

    @GetMapping(CREATOR_COMPANY)
    public ModelAndView getPage(ModelAndView model, Company company) {
        return new ModelResponseBuilder(model)
                .withView(CREATOR_COMPANY)
                .addResponseData(ResponseDataType.COMPANY, company)
                .build();
    }

    @PostMapping(value = CREATOR_COMPANY, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ModelAndView createCompany(@ModelAttribute @Valid Company company) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder();

        try {
            company = companyService.save(company);

            modelResponseBuilder.addResponseCode(ResponseCode.SUCCESS_SAVING_COMPANY, company.getName());
        } catch (EntityAlreadyExistsException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.COMPANY_ALREADY_EXIST, company.getName());
        }

        return getPage(modelResponseBuilder.build(), company);
    }
}
