/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.person;

import business.user.PersonManager;
import business.user.UserPictureManager;
import controller.AbstractController;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import model.files.Mime;
import model.files.UserPicture;
import model.person.Person;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.file.UploadedFile;

/**
 *
 * @author patri
 */
@Named
@RequestScoped
public class UserPictureController extends AbstractController {

    private UserPicture picture;

    @Inject
    PersonController personController;

    @EJB
    UserPictureManager upManager;
    
    @EJB
    PersonManager personManager;

    public void handleUserPictureUpload(FileUploadEvent event) {
        UploadedFile file = event.getFile();

        if (file != null && file.getContent() != null && file.getContent().length > 0 && file.getFileName() != null) {

            if (createSaveUserPicture(file)) {
                sendInfoMessage("Erfolg", this.picture.getName() + " wurde hochgeladen!");
            } else {
                sendErrorMessage("Fehler", "Es ist ein Fehler aufgetreten. Bitte Versuchen Sie es erneut!");
            }
        }
    }

    private boolean createSaveUserPicture(UploadedFile file) {
        picture = null;
        picture = personController.getActiveUser().getUserPicture();
        boolean isNew = picture == null;
        
        if (isNew) {
            picture = new UserPicture();
        }
        
        setData(picture, file);
        Person person = personManager.load(personController.getActiveUser());
        person.setUserPicture(picture);
        picture.setPerson(person);
        
        if (isNew) {
            upManager.create(picture);
        } else {
            upManager.edit(picture);
        }
        
        personManager.save(person);
        personController.reloadActivePerson();
        
        return true;
    }

    private void setData(UserPicture picture, UploadedFile file) {
        picture.setName(file.getFileName());
        picture.setFileData(file.getContent());
        picture.setMime(Mime.getByMimeType(file.getContentType()));
    }

    public long getMaxFileSize() {
        return UserPicture.getSizeLimit();
    }

    public String getFileTypesRE() {
        return UserPicture.getAllowedTypesRE();
    }
}
