at.fh.swenga.firefighters.controller.FireFighterController.java Source code

Java tutorial

Introduction

Here is the source code for at.fh.swenga.firefighters.controller.FireFighterController.java

Source

package at.fh.swenga.firefighters.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import at.fh.swenga.firefighters.dao.FireBrigadeRepository;
import at.fh.swenga.firefighters.dao.FireEngineAbbreviationRepository;
import at.fh.swenga.firefighters.dao.FireEngineRepository;
import at.fh.swenga.firefighters.dao.FireFighterRepository;
import at.fh.swenga.firefighters.dao.FireFighterStatusRepository;
import at.fh.swenga.firefighters.dao.ImageRepository;
import at.fh.swenga.firefighters.dao.MessageRepository;
import at.fh.swenga.firefighters.dao.RankRepository;
import at.fh.swenga.firefighters.dao.UserRepository;
import at.fh.swenga.firefighters.model.FireBrigadeModel;
import at.fh.swenga.firefighters.model.FireEngineAbbreviationModel;
import at.fh.swenga.firefighters.model.FireEngineModel;
import at.fh.swenga.firefighters.model.FireFighterModel;
import at.fh.swenga.firefighters.model.FireFighterStatusModel;
import at.fh.swenga.firefighters.model.ImageModel;
import at.fh.swenga.firefighters.model.MessageModel;
import at.fh.swenga.firefighters.model.MyUserPrincipal;
import at.fh.swenga.firefighters.model.RankModel;
import at.fh.swenga.firefighters.model.User;
import at.fh.swenga.firefighters.model.UserDto;
import at.fh.swenga.firefighters.service.IUserService;
import at.fh.swenga.firefighters.validation.EmailExistsException;
import at.fh.swenga.firefighters.validation.FireBrigadeExistsException;
import at.fh.swenga.firefighters.validation.InvalidOldPasswordException;
import at.fh.swenga.firefighters.validation.MapUtil;

@Controller
@ControllerAdvice
public class FireFighterController {

    @Autowired
    FireBrigadeRepository fireBrigadeRepository;

    @Autowired
    FireFighterRepository fireFighterRepository;

    @Autowired
    FireEngineRepository fireEngineRepository;

    @Autowired
    MessageRepository messageRepository;

    @Autowired
    RankRepository rankRepository;

    @Autowired
    FireFighterStatusRepository statusRepository;

    @Autowired
    FireEngineAbbreviationRepository fireEngineAbbreviationRepository;

    @Autowired
    private MessageSource messages;

    @Autowired
    UserRepository userRepository;

    @Autowired
    ImageRepository imageRepository;

    @Autowired
    private IUserService userService;

    @ModelAttribute
    public void addAttributes(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            model.addAttribute("count", messageRepository.countByRole("admin"));
        } else if (request.isUserInRole("ROLE_ADMIN")) {
            model.addAttribute("count",
                    messageRepository.countByFireBrigadeAndRole(getSessionFireBrigade(), "user"));
        } else {

        }
    }

    public FireBrigadeModel getSessionFireBrigade() {
        MyUserPrincipal userDetails = (MyUserPrincipal) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
        return userDetails.getFireBrigade();
    }

    public MyUserPrincipal getSessionUser() {
        MyUserPrincipal userDetails = (MyUserPrincipal) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
        return userDetails;
    }

    @RequestMapping(value = { "/", "index" })
    public String index(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
            model.addAttribute("fireBrigades", fireBrigades);
            float males = fireFighterRepository.countByGender("m");
            float females = fireFighterRepository.countByGender("w");
            float sumFighters = males + females;
            float percentFem = females / sumFighters * 100;
            float percentMal = males / sumFighters * 100;
            percentFem = BigDecimal.valueOf(percentFem).setScale(2, RoundingMode.HALF_UP).floatValue();
            percentMal = BigDecimal.valueOf(percentMal).setScale(2, RoundingMode.HALF_UP).floatValue();
            model.addAttribute("males", percentMal);
            model.addAttribute("females", percentFem);
            model.addAttribute("sumFighters", sumFighters);
            List<Object[]> topFireBrigades = fireFighterRepository.groupByFireBrigade();
            Map<String, BigInteger> topFireBrigadesMap = topFireBrigades.stream().collect(Collectors.toMap(
                    a -> (String) fireBrigadeRepository.findById((int) a[1]).getName(), a -> (BigInteger) a[0]));
            Map<String, BigInteger> sortedTopFireBrigadesMap = MapUtil.sortByValue(topFireBrigadesMap);
            model.addAttribute("sortedTopFireBrigades", sortedTopFireBrigadesMap);

        } else if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")
                && (request.isUserInRole("ROLE_ADMIN") || request.isUserInRole("ROLE_USER"))) {
            List<FireFighterModel> fireFighters = fireFighterRepository.findByFireBrigade(getSessionFireBrigade());
            model.addAttribute("fireFighters", fireFighters);
        }
        return "index";
    }

    @RequestMapping(value = { "feuerwehr" })
    public String feuerwehr(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
            model.addAttribute("fireBrigades", fireBrigades);
        } else {
            FireBrigadeModel fireBrigade = fireBrigadeRepository.findById(getSessionFireBrigade().getId());
            model.addAttribute("fireBrigades", fireBrigade);
        }
        return "feuerwehr";
    }

    /* normal nicht bentigt, da Feuerwehren nur ber das Registrierungsformular hinzugefgt werden sollen
    @RequestMapping(value = "addFireBrigade", method = RequestMethod.GET)
    public String showAddFireBrigadeForm(Model model) {
       return "editFireBrigade";
    }
    */

    // Error/Success meldungen unbedingt noch abfangen...
    // deswegen da auch kein check ob er die feuerwehr bearbeiten darf.
    // role check sonst ned vergessen aba normal gehts eh ned anders

    /* normal nicht bentigt, da Feuerwehren nur ber das Registrierungsformular hinzugefgt werden sollen
    @RequestMapping(value = "addFireBrigade", method = RequestMethod.POST)
    public String addFireBrigade(@Valid @ModelAttribute FireBrigadeModel newFireBrigade, BindingResult bindingResult, Model model) {
       if (bindingResult.hasErrors()) {
     String errorMessage = "";
     for (FieldError fieldError : bindingResult.getFieldErrors()) {
        errorMessage += fieldError.getField() + " ist falsch";
     }
     model.addAttribute("errorMessage", errorMessage);
     return "forward:feuerwehr";
       }
       fireBrigadeRepository.save(newFireBrigade);
       model.addAttribute("message", "Neue Feuerwehr " + newFireBrigade.getName() + " hinzugefgt.");
        
       return "forward:feuerwehr";
    } */

    @RequestMapping(value = "editFireBrigade", method = RequestMethod.GET)
    public String showEditFireBrigade(Model model, @RequestParam int id, HttpServletRequest request) {
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireBrigadeModel fireBrigade = fireBrigadeRepository.findById(id);
            if (fireBrigade != null) {
                model.addAttribute("fireBrigade", fireBrigade);
                return "editFireBrigade";
            } else {
                model.addAttribute("errorMessage", "Feuerwehr mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:feuerwehr";
            }
        } else {
            FireBrigadeModel fireBrigade = fireBrigadeRepository.findByIdAndName(id,
                    getSessionFireBrigade().getName());

            if (fireBrigade != null) {
                model.addAttribute("fireBrigade", fireBrigade);
                return "editFireBrigade";
            } else {
                model.addAttribute("errorMessage", "Feuerwehr mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:feuerwehr";
            }
        }

    }

    @RequestMapping(value = "editFireBrigade", method = RequestMethod.POST)
    public String editFireBrigade(@Valid @ModelAttribute FireBrigadeModel changedFireBrigade,
            BindingResult bindingResult, Model model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist ungltig!";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:feuerwehr";
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireBrigadeModel fireBrigade = fireBrigadeRepository.findById(changedFireBrigade.getId());

            if (fireBrigade == null) {
                model.addAttribute("errorMessage", "Diese Feuerwehr kann nicht bearbeitet werden!");
            } else {
                fireBrigade.setName(changedFireBrigade.getName());
                fireBrigade.setPostalCode(changedFireBrigade.getPostalCode());
                fireBrigade.setPostTown(changedFireBrigade.getPostTown());
                fireBrigade.setStreetName(changedFireBrigade.getStreetName());
                fireBrigadeRepository.save(fireBrigade);
                model.addAttribute("message",
                        "Feuerwehr " + changedFireBrigade.getName() + " wurde erfolgreich gendert.");
            }
            return "forward:feuerwehr";

        } else {
            FireBrigadeModel fireBrigade = fireBrigadeRepository.findByIdAndName(changedFireBrigade.getId(),
                    getSessionFireBrigade().getName());

            if (fireBrigade == null) {
                model.addAttribute("errorMessage", "Diese Feuerwehr kann nicht bearbeitet werden!");
                System.out.println("Falsche Feuerwehr!");
            } else {
                fireBrigade.setName(changedFireBrigade.getName());
                fireBrigade.setPostalCode(changedFireBrigade.getPostalCode());
                fireBrigade.setPostTown(changedFireBrigade.getPostTown());
                fireBrigade.setStreetName(changedFireBrigade.getStreetName());
                fireBrigadeRepository.save(fireBrigade);
                model.addAttribute("message",
                        "Feuerwehr " + changedFireBrigade.getName() + " wurde erfolgreich gendert!");
                new SecurityContextLogoutHandler().logout(request, null, null);
                return "redirect:login";
            }
            return "forward:feuerwehr";
        }
    }

    @Transactional
    @RequestMapping("deleteFireBrigade")
    public String deleteFireBrigade(Model model, @RequestParam int id, HttpServletRequest request) {
        FireBrigadeModel deletedFireBrigade = fireBrigadeRepository.findById(id);

        if (!fireFighterRepository.findByFireBrigade_Id(id).isEmpty()) {
            System.out.println(fireFighterRepository.findByFireBrigade_Id(id));
            model.addAttribute("errorMessage", "Lschen Sie zuerst alle Mitglieder!");
            return "forward:feuerwehr";
        }
        if (!fireEngineRepository.findByFireBrigade_Id(id).isEmpty()) {
            model.addAttribute("errorMessage", "Lschen Sie zuerst alle Fahrzeuge!");
            return "forward:feuerwehr";
        }
        if (deletedFireBrigade == null) {
            model.addAttribute("errorMessage", "Feuerwehr konnte nicht gefunden werden.");
            return "forward:feuerwehr";
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            User user = userRepository.findByFireBrigade(deletedFireBrigade);
            if (user == null) {
                model.addAttribute("errorMessage", "Es gibt keinen dazugehrigen User!");
                return "forward:feuerwehr";
            }
            fireBrigadeRepository.delete(id);
            model.addAttribute("message", "Feuerwehr Nr." + id + " " + "wurde erfolgreich gelscht!");
            System.out.println(user);
            userRepository.delete(user);
        }
        return "forward:feuerwehr";
    }

    @RequestMapping(value = { "mitglieder" })
    public String mitglieder(Model model, HttpServletRequest request) {
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<FireFighterModel> fireFighters = fireFighterRepository.findAll();
            model.addAttribute("fireFighters", fireFighters);
        } else {
            List<FireFighterModel> fireFighters = fireFighterRepository.findByFireBrigade(getSessionFireBrigade());
            model.addAttribute("fireFighters", fireFighters);
        }
        return "mitglieder";
    }

    @RequestMapping(value = "addFireFighter", method = RequestMethod.GET)
    public String showAddFireFighterForm(Model model) {
        List<RankModel> ranks = rankRepository.findAll();
        model.addAttribute("ranks", ranks);
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        List<FireFighterStatusModel> status = statusRepository.findAll();
        model.addAttribute("status", status);
        return "editFireFighter";
    }

    @RequestMapping(value = "addFireFighter", method = RequestMethod.POST)
    public String addFireFighter(@Valid @ModelAttribute FireFighterModel newFireFighter,
            BindingResult bindingResult, Model model, HttpServletRequest request) {

        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage = fieldError.getField() + " ist falsch";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:mitglieder";
        }
        if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            newFireFighter.setFireBrigade(getSessionFireBrigade());
        }
        fireFighterRepository.save(newFireFighter);
        model.addAttribute("message",
                "Mitglied " + newFireFighter.getName() + " " + newFireFighter.getSurname() + " hinzugefgt.");

        return "forward:mitglieder";
    }

    @RequestMapping(value = "editFireFighter", method = RequestMethod.GET)
    public String showEditFireFighter(Model model, @RequestParam int id, HttpServletRequest request) {
        List<RankModel> ranks = rankRepository.findAll();
        model.addAttribute("ranks", ranks);
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        List<FireFighterStatusModel> status = statusRepository.findAll();
        model.addAttribute("status", status);
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireFighterModel fireFighter = fireFighterRepository.findById(id);
            if (fireFighter != null) {
                model.addAttribute("fireFighter", fireFighter);
                return "editFireFighter";
            } else {
                model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
                return "forward:mitglieder";
            }
        } else {
            FireFighterModel fireFighter = fireFighterRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                    id);

            if (fireFighter != null) {
                model.addAttribute("fireFighter", fireFighter);
                return "editFireFighter";
            } else {
                model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
                return "forward:mitglieder";
            }
        }
    }

    @RequestMapping(value = "editFireFighter", method = RequestMethod.POST)
    public String editFireFighter(@Valid @ModelAttribute FireFighterModel changedFireFighter,
            BindingResult bindingResult, Model model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage = fieldError.getField() + " ist ungltig!";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:mitglieder";
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireFighterModel fireFighter = fireFighterRepository.findById(changedFireFighter.getId());

            if (fireFighter == null) {
                model.addAttribute("errorMessage", "Dieses Mitglied kann nicht bearbeitet werden!");
            } else {
                fireFighter.setTitle(changedFireFighter.getTitle());
                fireFighter.setName(changedFireFighter.getName());
                fireFighter.setSurname(changedFireFighter.getSurname());
                fireFighter.setRank(changedFireFighter.getRank());
                fireFighter.setFireBrigade(changedFireFighter.getFireBrigade());
                fireFighter.setFireFighterStatus(changedFireFighter.getFireFighterStatus());
                fireFighter.setStreetName(changedFireFighter.getStreetName());
                fireFighter.setPostalCode(changedFireFighter.getPostalCode());
                fireFighter.setPostTown(changedFireFighter.getPostTown());
                fireFighter.setGender(changedFireFighter.getGender());
                fireFighter.setDayOfBirth(changedFireFighter.getDayOfBirth());
                fireFighterRepository.save(fireFighter);
                model.addAttribute("message", "Mitglied " + changedFireFighter.getName() + " "
                        + changedFireFighter.getSurname() + " " + "wurde gendert.");
            }
            return "forward:mitglieder";

        } else {
            FireFighterModel fireFighter = fireFighterRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                    changedFireFighter.getId());

            if (fireFighter == null) {
                model.addAttribute("errorMessage", "Dieses Mitglied kann nicht bearbeitet werden!");
                System.out.println("Falsches Mitglied!");
            } else {
                fireFighter.setTitle(changedFireFighter.getTitle());
                fireFighter.setName(changedFireFighter.getName());
                fireFighter.setSurname(changedFireFighter.getSurname());
                fireFighter.setRank(changedFireFighter.getRank());
                fireFighter.setFireBrigade(getSessionFireBrigade());
                fireFighter.setFireFighterStatus(changedFireFighter.getFireFighterStatus());
                fireFighter.setStreetName(changedFireFighter.getStreetName());
                fireFighter.setPostalCode(changedFireFighter.getPostalCode());
                fireFighter.setPostTown(changedFireFighter.getPostTown());
                fireFighter.setGender(changedFireFighter.getGender());
                fireFighter.setDayOfBirth(changedFireFighter.getDayOfBirth());
                fireFighterRepository.save(fireFighter);
                model.addAttribute("message", "Mitglied " + changedFireFighter.getName() + " "
                        + changedFireFighter.getSurname() + " " + "wurde gendert.");
            }
            return "forward:mitglieder";
        }
    }

    @Transactional
    @RequestMapping("deleteFireFighter")
    public String deleteFireFighter(Model model, @RequestParam int id, HttpServletRequest request) {
        //Error check? 
        // Error message wie oben ausgeben andi
        FireFighterModel deletedFireFighter = fireFighterRepository.findById(id);
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            fireFighterRepository.delete(id);
        } else {
            fireFighterRepository.deleteByFireBrigadeAndId(getSessionFireBrigade(), id);
        }
        model.addAttribute("message", "Mitglied " + " " + deletedFireFighter.getName() + " "
                + deletedFireFighter.getSurname() + " " + "wurde gelscht");
        return "forward:mitglieder";
    }

    @RequestMapping(value = { "status" })
    public String status(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<FireFighterStatusModel> statuss = statusRepository.findAll();
            model.addAttribute("statuss", statuss);
        }
        return "status";
    }

    @RequestMapping(value = "addStatus", method = RequestMethod.GET)
    public String addStatus(Model model) {
        return "editStatus";
    }

    @RequestMapping(value = "addStatus", method = RequestMethod.POST)
    public String addStatus(@Valid @ModelAttribute FireFighterStatusModel newStatus, BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist falsch";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:status";
        }
        statusRepository.save(newStatus);
        model.addAttribute("message", "Neuer Mitgliederstatus " + newStatus.getDescription() + " hinzugefgt.");

        return "forward:status";
    }

    @RequestMapping(value = "editStatus", method = RequestMethod.GET)
    public String showEditStatus(Model model, @RequestParam int id, HttpServletRequest request) {
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireFighterStatusModel status = statusRepository.findById(id);
            if (status != null) {
                model.addAttribute("status", status);
                return "editStatus";
            } else {
                model.addAttribute("errorMessage",
                        "Mitgliederstatus mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:status";
            }
        } else {
            FireFighterStatusModel status = statusRepository.findById(id);

            if (status != null) {
                model.addAttribute("status", status);
                return "editStatus";
            } else {
                model.addAttribute("errorMessage",
                        "Mitgliederstatus mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:status";
            }
        }

    }

    @RequestMapping(value = "editStatus", method = RequestMethod.POST)
    public String editStatus(@Valid @ModelAttribute FireFighterStatusModel changedStatus,
            BindingResult bindingResult, Model model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist ungltig!";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:status";
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireFighterStatusModel status = statusRepository.findById(changedStatus.getId());

            if (status == null) {
                model.addAttribute("errorMessage", "Diese Feuerwehr kann nicht bearbeitet werden!");
            } else {
                status.setDescription(changedStatus.getDescription());
                statusRepository.save(status);
                model.addAttribute("message",
                        "Mitgliederstatus " + changedStatus.getDescription() + " wurde erfolgreich gendert.");
            }
            return "forward:status";

        } else {
            FireFighterStatusModel status = statusRepository.findById(changedStatus.getId());

            if (status == null) {
                model.addAttribute("errorMessage", "Dieser Mitgliederstatus kann nicht bearbeitet werden!");
                System.out.println("Falscher Mitgliederstatus!");
            } else {
                status.setDescription(changedStatus.getDescription());
                statusRepository.save(status);
                model.addAttribute("message",
                        "Mitgliederstatus " + changedStatus.getDescription() + " wurde erfolgreich gendert!");
            }
            return "forward:status";
        }
    }

    @RequestMapping(value = { "fahrzeuge" })
    public String fahrzeuge(Model model, HttpServletRequest request) {
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<FireEngineModel> fireEngines = fireEngineRepository.findAll();
            model.addAttribute("fireEngines", fireEngines);
        } else {
            List<FireEngineModel> fireEngines = fireEngineRepository.findByFireBrigade(getSessionFireBrigade());
            model.addAttribute("fireEngines", fireEngines);
        }
        return "fahrzeuge";
    }

    @RequestMapping(value = "addFireEngine", method = RequestMethod.GET)
    public String showAddFireEngineForm(Model model) {
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        List<FireEngineAbbreviationModel> fireEngineAbbreviations = fireEngineAbbreviationRepository.findAll();
        model.addAttribute("fireEngineAbbreviations", fireEngineAbbreviations);
        return "editFireEngine";
    }

    @RequestMapping(value = "addFireEngine", method = RequestMethod.POST)
    public String addFireEngine(@Valid @ModelAttribute FireEngineModel newFireEngine, BindingResult bindingResult,
            Model model, HttpServletRequest request) {
        System.out.println(newFireEngine);
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage = fieldError.getField() + " ist falsch";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:fahrzeuge";
        }
        if (newFireEngine.getActive() == null) {
            newFireEngine.setActive(false);
        }

        if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            newFireEngine.setFireBrigade(getSessionFireBrigade());
        }
        fireEngineRepository.save(newFireEngine);
        model.addAttribute("message", "Fahrzeug " + newFireEngine.getModel() + " hinzugefgt.");

        return "forward:fahrzeuge";
    }

    @RequestMapping(value = "editFireEngine", method = RequestMethod.GET)
    public String showEditFireEngine(Model model, @RequestParam int id, HttpServletRequest request) {
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        List<FireEngineAbbreviationModel> fireEngineAbbreviations = fireEngineAbbreviationRepository.findAll();
        model.addAttribute("fireEngineAbbreviations", fireEngineAbbreviations);
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireEngineModel fireEngine = fireEngineRepository.findById(id);
            if (fireEngine != null) {
                model.addAttribute("fireEngine", fireEngine);
                return "editFireEngine";
            } else {
                model.addAttribute("errorMessage", "Feuerwehr " + id + " konnte nicht gefunden werden.");
                return "forward:fahrzeuge";
            }
        } else {
            FireEngineModel fireEngine = fireEngineRepository.findByFireBrigadeAndId(getSessionFireBrigade(), id);

            if (fireEngine != null) {
                model.addAttribute("fireEngine", fireEngine);
                return "editFireEngine";
            } else {
                model.addAttribute("errorMessage", "Fahrzeug " + id + " konnte nicht gefunden werden.");
                return "forward:fahrzeuge";
            }
        }
    }

    @RequestMapping(value = "editFireEngine", method = RequestMethod.POST)
    public String editFireEngine(@Valid @ModelAttribute FireEngineModel changedFireEngine,
            BindingResult bindingResult, Model model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage = fieldError.getField() + " is invalid";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:fahrzeuge";
        }

        if (changedFireEngine.getActive() == null) {
            changedFireEngine.setActive(false);
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireEngineModel fireEngine = fireEngineRepository.findById(changedFireEngine.getId());

            if (fireEngine == null) {
                model.addAttribute("errorMessage", "Diese Fahrzeug kann nicht bearbeitet werden!");
            } else {
                fireEngine.setModel(changedFireEngine.getModel());
                fireEngine.setLicensePlate(changedFireEngine.getLicensePlate());
                fireEngine.setPerformance(changedFireEngine.getPerformance());
                fireEngine.setBuildYear(changedFireEngine.getBuildYear());
                fireEngine.setActive(changedFireEngine.getActive());
                fireEngine.setAbbreviation(changedFireEngine.getAbbreviation());
                fireEngine.setFireBrigade(changedFireEngine.getFireBrigade());
                fireEngineRepository.save(fireEngine);
                model.addAttribute("message", "Fahrzeug " + changedFireEngine.getModel() + " " + "wurde gendert.");
            }
            return "forward:fahrzeuge";

        } else {
            FireEngineModel fireEngine = fireEngineRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                    changedFireEngine.getId());

            if (fireEngine == null) {
                model.addAttribute("errorMessage", "Dieses Fahrzeug kann nicht bearbeitet werden!");
                System.out.println("Falsches Fahrzeug!");
            } else {
                fireEngine.setModel(changedFireEngine.getModel());
                fireEngine.setLicensePlate(changedFireEngine.getLicensePlate());
                fireEngine.setPerformance(changedFireEngine.getPerformance());
                fireEngine.setBuildYear(changedFireEngine.getBuildYear());
                fireEngine.setActive(changedFireEngine.getActive());
                fireEngine.setAbbreviation(changedFireEngine.getAbbreviation());
                fireEngine.setFireBrigade(getSessionFireBrigade());
                fireEngineRepository.save(fireEngine);
                model.addAttribute("message", "Fahrzeug " + changedFireEngine.getModel() + " " + "wurde gendert.");
            }
            return "forward:fahrzeuge";
        }
    }

    @Transactional
    @RequestMapping("deleteFireEngine")
    public String deleteFireEngine(Model model, @RequestParam int id, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            fireEngineRepository.delete(id);
        } else {
            fireEngineRepository.deleteByFireBrigadeAndId(getSessionFireBrigade(), id);
        }
        return "forward:fahrzeuge";
    }

    @RequestMapping(value = { "funktionen" })
    public String funktionen(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<FireEngineAbbreviationModel> fireEngineAbbreviations = fireEngineAbbreviationRepository.findAll();
            model.addAttribute("fireEngineAbbreviations", fireEngineAbbreviations);
        }
        return "funktionen";
    }

    @RequestMapping(value = "addFunction", method = RequestMethod.GET)
    public String showAddFunctionForm(Model model) {
        return "editFunction";
    }

    @RequestMapping(value = "addFunction", method = RequestMethod.POST)
    public String addFunction(@Valid @ModelAttribute FireEngineAbbreviationModel newFireEngineAbbreviation,
            BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist falsch";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:funktionen";
        }
        fireEngineAbbreviationRepository.save(newFireEngineAbbreviation);
        model.addAttribute("message",
                "Neue Fahrzeugfunktion " + newFireEngineAbbreviation.getDescription() + " hinzugefgt.");

        return "forward:feuerwehr";
    }

    @RequestMapping(value = "editFunction", method = RequestMethod.GET)
    public String showEditFunction(Model model, @RequestParam int id, HttpServletRequest request) {
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireEngineAbbreviationModel fireEngineAbbreviation = fireEngineAbbreviationRepository.findById(id);
            if (fireEngineAbbreviation != null) {
                model.addAttribute("fireEngineAbbreviation", fireEngineAbbreviation);
                return "editFunction";
            } else {
                model.addAttribute("errorMessage",
                        "Fahrzeugfunktion mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:funktionen";
            }
        } else {
            FireEngineAbbreviationModel fireEngineAbbreviation = fireEngineAbbreviationRepository.findById(id);

            if (fireEngineAbbreviation != null) {
                model.addAttribute("fireEngineAbbreviation", fireEngineAbbreviation);
                return "editFunction";
            } else {
                model.addAttribute("errorMessage",
                        "Fahrzeugfunktion mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:funktionen";
            }
        }

    }

    @RequestMapping(value = "editFunction", method = RequestMethod.POST)
    public String editFunction(@Valid @ModelAttribute FireEngineAbbreviationModel changedFireEngineAbbreviation,
            BindingResult bindingResult, Model model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist ungltig!";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:funktionen";
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireEngineAbbreviationModel fireEngineAbbreviation = fireEngineAbbreviationRepository
                    .findById(changedFireEngineAbbreviation.getId());

            if (fireEngineAbbreviation == null) {
                model.addAttribute("errorMessage", "Diese Fahrzeugfunktion kann nicht bearbeitet werden!");
            } else {
                fireEngineAbbreviation.setDescription(changedFireEngineAbbreviation.getDescription());
                fireEngineAbbreviation.setAbbreviation(changedFireEngineAbbreviation.getAbbreviation());
                fireEngineAbbreviation.setOperatingLife(changedFireEngineAbbreviation.getOperatingLife());
                fireEngineAbbreviationRepository.save(fireEngineAbbreviation);
                model.addAttribute("message", "Fahrzeugfunktion " + changedFireEngineAbbreviation.getDescription()
                        + " wurde erfolgreich gendert.");
            }
            return "forward:funktionen";

        } else {
            FireEngineAbbreviationModel fireEngineAbbreviation = fireEngineAbbreviationRepository
                    .findById(changedFireEngineAbbreviation.getId());

            if (fireEngineAbbreviation == null) {
                model.addAttribute("errorMessage", "Diese Fahrzeugfunktion kann nicht bearbeitet werden!");
                System.out.println("Falsche Fahrzeugfunktion!");
            } else {
                fireEngineAbbreviation.setDescription(changedFireEngineAbbreviation.getDescription());
                fireEngineAbbreviation.setAbbreviation(changedFireEngineAbbreviation.getAbbreviation());
                fireEngineAbbreviation.setOperatingLife(changedFireEngineAbbreviation.getOperatingLife());
                fireEngineAbbreviationRepository.save(fireEngineAbbreviation);
                model.addAttribute("message", "Fahrzeugfunktion " + changedFireEngineAbbreviation.getDescription()
                        + " wurde erfolgreich gendert!");
            }
            return "forward:funktionen";
        }
    }

    @RequestMapping(value = { "dienstgrade" })
    public String dienstgrade(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<RankModel> ranks = rankRepository.findAll();
            model.addAttribute("ranks", ranks);
        }
        return "dienstgrade";
    }

    @RequestMapping(value = "addRank", method = RequestMethod.GET)
    public String addRank(Model model) {
        return "editRank";
    }

    @RequestMapping(value = "addRank", method = RequestMethod.POST)
    public String addRank(@Valid @ModelAttribute RankModel newRank, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist falsch";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:dienstgrade";
        }
        rankRepository.save(newRank);
        model.addAttribute("message", "Neuer Dienstgrad " + newRank.getDescription() + " hinzugefgt.");

        return "forward:dienstgrade";
    }

    @RequestMapping(value = "editRank", method = RequestMethod.GET)
    public String showEditRank(Model model, @RequestParam int id, HttpServletRequest request) {
        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            RankModel rank = rankRepository.findById(id);
            if (rank != null) {
                model.addAttribute("rank", rank);
                return "editRank";
            } else {
                model.addAttribute("errorMessage",
                        "Dienstgrad mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:dienstgrade";
            }
        } else {
            RankModel rank = rankRepository.findById(id);

            if (rank != null) {
                model.addAttribute("rank", rank);
                return "editRank";
            } else {
                model.addAttribute("errorMessage",
                        "Dienstgrad mit der ID " + id + " konnte nicht gefunden werden.");
                return "forward:dienstgrade";
            }
        }

    }

    @RequestMapping(value = "editRank", method = RequestMethod.POST)
    public String editRank(@Valid @ModelAttribute RankModel changedRank, BindingResult bindingResult, Model model,
            HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            String errorMessage = "";
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMessage += fieldError.getField() + " ist ungltig!";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "forward:dienstgrade";
        }

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            RankModel rank = rankRepository.findById(changedRank.getId());

            if (rank == null) {
                model.addAttribute("errorMessage", "Dieser Dienstgrad kann nicht bearbeitet werden!");
            } else {
                rank.setDescription(changedRank.getDescription());
                rank.setAbbreviation(changedRank.getAbbreviation());
                rankRepository.save(rank);
                model.addAttribute("message",
                        "Dienstgrad " + changedRank.getDescription() + " wurde erfolgreich gendert.");
            }
            return "forward:dienstgrade";

        } else {
            RankModel rank = rankRepository.findById(changedRank.getId());

            if (rank == null) {
                model.addAttribute("errorMessage", "Dieser Dienstgrad kann nicht bearbeitet werden!");
                System.out.println("Falscher Dienstgrad!");
            } else {
                rank.setDescription(changedRank.getDescription());
                rank.setAbbreviation(changedRank.getAbbreviation());
                rankRepository.save(rank);
                model.addAttribute("message",
                        "Dienstgrad " + changedRank.getDescription() + " wurde erfolgreich gendert!");
            }
            return "forward:dienstgrade";
        }
    }

    @RequestMapping(value = { "contact" }, method = RequestMethod.POST)
    public String contact(Model model, @RequestParam String message, @RequestParam String role) {
        MessageModel fullMessage = new MessageModel(getSessionUser().getEmail(), getSessionUser().getSurname(),
                getSessionUser().getName(), message, role, new Date(), getSessionFireBrigade());
        messageRepository.save(fullMessage);
        return "index";
    }

    @RequestMapping(value = { "nachrichten" })
    public String nachrichten(Model model, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            List<MessageModel> messages = messageRepository.findByRole("admin");
            model.addAttribute("messages", messages);
        } else {
            List<MessageModel> messages = messageRepository.findByFireBrigadeAndRole(getSessionFireBrigade(),
                    "user");
            model.addAttribute("messages", messages);
        }
        // model.addAttribute("count", fireBrigades.size());
        return "nachrichten";
    }

    @RequestMapping("deleteMessage")
    public String deleteData(Model model, @RequestParam int id) {
        messageRepository.delete(id);
        return "forward:nachrichten";
    }

    @RequestMapping(value = { "profile" })
    public String profile(Model model) {
        return "profile";
    }

    @RequestMapping(value = "editProfile", method = RequestMethod.POST)
    public String editProfile(Model model, @RequestParam String firstname, @RequestParam String lastname,
            @RequestParam String email, HttpServletRequest request) {
        User currentUser = userRepository.findById(getSessionUser().getId());
        currentUser.setName(firstname);
        currentUser.setSurname(lastname);
        currentUser.setEmail(email);
        userRepository.save(currentUser);
        new SecurityContextLogoutHandler().logout(request, null, null);
        return "redirect:login";
    }

    @RequestMapping(value = { "newFireBrigadeUser" })
    public String newFireBrigadeUser(Model model) {
        return "newFireBrigadeUser";
    }

    @RequestMapping(value = "newFireBrigadeUser", method = RequestMethod.GET)
    public String showNewFireBrigadeUserForm(WebRequest request, Model model) {
        UserDto userDto = new UserDto();
        userDto.setFireBrigadeName(getSessionFireBrigade().getName());
        userDto.setFireBrigadeStreetName(getSessionFireBrigade().getStreetName());
        userDto.setFireBrigadeTown(getSessionFireBrigade().getPostTown());
        userDto.setFireBrigadePostalCode(getSessionFireBrigade().getPostalCode());
        model.addAttribute("user", userDto);
        return "newFireBrigadeUser";
    }

    @RequestMapping(value = "newFireBrigadeUser", method = RequestMethod.POST)
    public ModelAndView newFireBrigadeUserUserAccount(@ModelAttribute("user") @Valid UserDto accountDto,
            BindingResult result, WebRequest request, Errors errors) {
        System.out.println(accountDto);
        accountDto.setFireBrigadeName(getSessionFireBrigade().getName());
        accountDto.setFireBrigadeStreetName(getSessionFireBrigade().getStreetName());
        accountDto.setFireBrigadeTown(getSessionFireBrigade().getPostTown());
        accountDto.setFireBrigadePostalCode(getSessionFireBrigade().getPostalCode());
        System.out.println(accountDto);
        System.out.println(result);
        User registered = new User();
        if (!result.hasErrors()) {
            registered = createAccount(accountDto, result);

        }
        if (registered == null) {
            result.rejectValue("email", "message.regError");
        }
        if (result.hasErrors()) {
            return new ModelAndView("newFireBrigadeUser", "user", accountDto);
        } else {
            return new ModelAndView("successFireBrigadeUser", "user", accountDto);
        }
    }

    private User createUserAccount(UserDto accountDto, BindingResult result) {
        User registered = null;
        try {
            registered = userService.registerNewUserAccount(accountDto);
        } catch (EmailExistsException | FireBrigadeExistsException e) {
            return null;
        }
        return registered;
    }

    private User createAccount(UserDto accountDto, BindingResult result) {
        User registered = null;
        try {
            registered = userService.registerNewAccount(accountDto, getSessionFireBrigade());
        } catch (EmailExistsException e) {
            return null;
        }
        return registered;
    }

    @RequestMapping(value = "registration", method = RequestMethod.GET)
    public String showRegistrationForm(WebRequest request, Model model) {
        UserDto userDto = new UserDto();
        model.addAttribute("user", userDto);
        return "registration";
    }

    @RequestMapping(value = "registration", method = RequestMethod.POST)
    public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result,
            WebRequest request, Errors errors) {
        User registered = new User();
        if (!result.hasErrors()) {
            registered = createUserAccount(accountDto, result);

        }
        if (registered == null) {
            result.rejectValue("email", "message.regError");
        }
        if (result.hasErrors()) {
            return new ModelAndView("registration", "user", accountDto);
        } else {
            return new ModelAndView("successRegister", "user", accountDto);
        }
    }

    @RequestMapping(value = { "kontakt" })
    public String kontakt(Model model) {
        return "kontakt";
    }

    @RequestMapping(value = { "impressum" })
    public String impressum(Model model) {
        return "impressum";
    }

    @RequestMapping(value = { "impressum_login" })
    public String impressum_login(Model model) {
        return "impressum_login";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String handleLogin() {
        return "login";
    }

    @RequestMapping(value = { "hilfe" })
    public String hilfe(Model model) {
        return "hilfe";
    }

    @RequestMapping(value = "editPassword", method = RequestMethod.GET)
    public String updatePassword(Model model) {
        return "editPassword";
    }

    @RequestMapping(value = "editPassword", method = RequestMethod.POST)
    public String updatePassword(Model model, @RequestParam String password, @RequestParam String oldPassword) {
        User user = userService.findUserById(getSessionUser().getId());

        if (!userService.checkIfValidOldPassword(user, oldPassword)) {
            throw new InvalidOldPasswordException();
        }
        userService.changeUserPassword(user, password);
        return "forward:profile";
    }

    @RequestMapping(value = { "find" })
    public String find(Model model, @RequestParam String searchString, @RequestParam String searchType) {
        List<FireFighterModel> fireFighters = null;

        switch (searchType) {
        case "query1":
            fireFighters = fireFighterRepository.findAll();
            break;
        case "query2":
            fireFighters = fireFighterRepository.findBySurname(searchString);
            break;
        case "query3":
            fireFighters = fireFighterRepository.findByName(searchString);
            break;
        case "query4":
            fireFighters = fireFighterRepository.findByWhateverName(searchString);
            break;
        case "query5":
            fireFighters = fireFighterRepository.findByRank_Abbreviation(searchString);
            break;
        case "query6":
            fireFighters = fireFighterRepository.findByFireFighterStatus_Description(searchString);
            break;
        case "query7":
            fireFighters = fireFighterRepository.findByStreetName(searchString);
            break;
        case "query8":
            fireFighters = fireFighterRepository.findByPostalCode(searchString);
            break;
        case "query9":
            fireFighters = fireFighterRepository.findByPostTown(searchString);
            break;
        case "query10":
            fireFighters = fireFighterRepository.findByGender(searchString);
            break;
        case "query11":
            fireFighters = fireFighterRepository.findByNameContainingOrSurnameContainingAllIgnoreCase(searchString,
                    searchString);
            break;
        case "query12":
            fireFighters = fireFighterRepository.findByFireBrigade_Name(searchString);
            break;
        case "query13":
            fireFighters = fireFighterRepository.findBySurnameContainingAllIgnoreCase(searchString);
            break;
        case "query14":
            fireFighters = fireFighterRepository.findByNameContainingAllIgnoreCase(searchString);
            break;
        default:
            fireFighters = fireFighterRepository.findAll();
        }
        model.addAttribute("fireFighters", fireFighters);

        return "mitglieder";
    }

    @RequestMapping(value = { "findFireEngines" })
    public String findFireEngines(Model model, @RequestParam String searchString, @RequestParam String searchType) {
        List<FireEngineModel> fireEngines = null;

        switch (searchType) {
        case "query1":
            fireEngines = fireEngineRepository.findAll();
            break;
        case "query2":
            fireEngines = fireEngineRepository.findAllByOrderByModel();
            break;
        case "query3":
            fireEngines = fireEngineRepository.findAllByOrderByPerformance();
            break;
        case "query4":
            fireEngines = fireEngineRepository.findAllByOrderByBuildYear();
            break;
        case "query5":
            fireEngines = fireEngineRepository.findByActive(searchString);
            break;
        case "query6":
            fireEngines = fireEngineRepository.findByAbbreviation_Abbreviation(searchString);
            break;
        case "query7":
            fireEngines = fireEngineRepository.findByModelContainingAllIgnoreCase(searchString);
            break;
        default:
            fireEngines = fireEngineRepository.findAll();
        }
        model.addAttribute("fireEngines", fireEngines);

        return "fahrzeuge";
    }

    @RequestMapping(value = { "findFireBrigades" })
    public String findFireBrigades(Model model, @RequestParam String searchString,
            @RequestParam String searchType) {
        List<FireBrigadeModel> fireBrigades = null;

        switch (searchType) {
        case "query1":
            fireBrigades = fireBrigadeRepository.findAll();
            break;
        case "query2":
            fireBrigades = fireBrigadeRepository.findByName(searchString);
            break;
        case "query3":
            fireBrigades = fireBrigadeRepository.findByPostalCode(searchString);
            break;
        case "query4":
            fireBrigades = fireBrigadeRepository.findByPostTown(searchString);
            break;
        case "query5":
            fireBrigades = fireBrigadeRepository.findAllByOrderByName();
            break;
        case "query6":
            fireBrigades = fireBrigadeRepository.findAllByOrderByPostTown();
            break;
        case "query7":
            fireBrigades = fireBrigadeRepository.findByNameContainingAllIgnoreCase(searchString);
            break;
        default:
            fireBrigades = fireBrigadeRepository.findAll();
        }
        model.addAttribute("fireBrigades", fireBrigades);

        return "feuerwehr";
    }

    @RequestMapping(value = { "report" })
    public String report(Model model, @RequestParam(required = false) String excel) {

        List<FireEngineModel> fireEngines = fireEngineRepository.findAll();

        // Store the fireEngines in the model, so the reports can access them
        model.addAttribute("fireEngines", fireEngines);

        // Which submit button was pressed? -> call the right report view
        if (StringUtils.isNoneEmpty(excel)) {
            return "excelReport";
        } else {
            return "forward:list";
        }
    }

    @RequestMapping(value = { "reportFireFighters" })
    public String reportFireFighters(Model model, @RequestParam(required = false) String excel) {

        List<FireFighterModel> fireFighters = fireFighterRepository.findAll();

        // Store the fireEngines in the model, so the reports can access them
        model.addAttribute("fireFighters", fireFighters);

        // Which submit button was pressed? -> call the right report view
        if (StringUtils.isNoneEmpty(excel)) {
            return "excelReportFireFighter";
        } else {
            return "forward:list";
        }
    }

    @RequestMapping(value = { "uploadImage" })
    public String uploadImage(Model model, @RequestParam int id, HttpServletRequest request) {

        if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
            FireFighterModel fireFighter = fireFighterRepository.findById(id);
            if (fireFighter != null) {
                model.addAttribute("fireFighter", fireFighter);
                return "uploadImage";
            } else {
                model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
                return "forward:mitglieder";
            }
        } else {
            FireFighterModel fireFighter = fireFighterRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                    id);

            if (fireFighter != null) {
                model.addAttribute("fireFighter", fireFighter);
                return "uploadImage";
            } else {
                model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
                return "forward:mitglieder";
            }
        }

    }

    /**
     * Save uploaded file to the database (as 1:1 relationship to fireFighter)
     * @param model
     * @param fireFighterId
     * @param file
     * @return
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String uploadDocument(Model model, @RequestParam("id") int fireFighterId,
            @RequestParam("myImage") MultipartFile file) {
        try {

            FireFighterModel fireFighter = fireFighterRepository.findOne(fireFighterId);
            // Already a document available -> delete it
            if (fireFighter.getImage() != null) {
                imageRepository.delete(fireFighter.getImage());
                // Don't forget to remove the relationship too 
                fireFighter.setImage(null);
            }

            //Create a new document and set all available infos 
            ImageModel img = new ImageModel();
            img.setContent(file.getBytes());
            img.setContentType(file.getContentType());
            img.setCreated(new Date());
            img.setFilename(file.getOriginalFilename());
            img.setName(file.getName());
            fireFighter.setImage(img);
            fireFighterRepository.save(fireFighter);
        } catch (Exception e) {
            model.addAttribute("errorMessage", "Error:" + e.getMessage());
        }

        return "forward:mitglieder";
    }

    @RequestMapping("/download")
    public void download(@RequestParam("imageId") int imageId, HttpServletResponse response) {
        ImageModel img = imageRepository.findOne(imageId);

        try {
            response.setHeader("Content-Disposition", "inline;filename=\"" + img.getFilename() + "\"");
            OutputStream out = response.getOutputStream();
            // application/octet-stream
            response.setContentType(img.getContentType());
            out.write(img.getContent());
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ExceptionHandler(Exception.class)
    public String handleAllException(Exception ex) {
        return "error";
    }

}