package com.nisum.controller;

import com.nisum.dto.EmployeeDto;
import com.nisum.model.impl.EmployeeImp;
import com.nisum.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

@Controller
public class EmployeeController {

  @Autowired
  EmployeeService employeeService;

  @RequestMapping(value = "/", method = RequestMethod.GET)
  public String index(Model model) {
    Collection<EmployeeImp> employeeList = employeeService.getAllEmployees();
    model.addAttribute("employees", employeeList);
    return "index";
  }

  @RequestMapping(value = "/new", method = RequestMethod.GET)
  public String newEmployee(Model model){
    model.addAttribute("employee", new EmployeeDto());
    return "new";
  }

  @RequestMapping(value = "/create", method = RequestMethod.POST)
  public String createEmployee(@ModelAttribute("employee") EmployeeDto employeeDto,
                               BindingResult bindingResult) {
    employeeService.createEmployee(employeeDto);
    return "redirect:/";
  }

  @RequestMapping(value="/delete/{id}", method = RequestMethod.POST)
  public String deleteEmployee(@PathVariable("id") int id){
    employeeService.delete(id);
    return "redirect:/";
  }

  @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
  public String editEmployee(@PathVariable("id") int id, Model model){
    EmployeeImp employeeImp = employeeService.getEmployeeById(id);
    EmployeeDto employeeDto = new EmployeeDto();
    employeeDto.setFirstName(employeeImp.getFirstName());
    employeeDto.setLastName(employeeImp.getLastName());
    // employeeDto.setJobTitle(employeeImp.getJobRole().getTitle());
    model.addAttribute("employee", employeeDto);
    model.addAttribute("employeeId", id);
    return "edit";
  }

  @RequestMapping(value="/update/{id}", method = RequestMethod.POST)
  public String updateEmployee(@ModelAttribute("employee") EmployeeDto employeeDto, 
                              @PathVariable("id") int id){
    employeeService.update(id, employeeDto);
    return "redirect:/";
  }  

}
