/**
 * 
 */
package org.richfaces.realworld.ui;

import java.io.File;

import javax.faces.model.SelectItem;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.core.Events;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;
import org.richfaces.realworld.domain.Sex;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.manager.FileManager;
import org.richfaces.realworld.manager.Model;
import org.richfaces.realworld.manager.NavigationEnum;
import org.richfaces.realworld.service.Constants;
import org.richfaces.realworld.service.FlushStrategy;
import org.richfaces.realworld.service.IUserAction;

/**
 * @author Andrey Markavtsov
 *
 */
@Name("userPrefsBean")
@Scope(ScopeType.SESSION)
public class UserPrefsHelper {
	
	@In IUserAction userAction;
	@In FileManager fileManager;
	@In @Out Model model;
	@In @Out User user;
	
	Boolean avatarModalOpened = false;
	
	File avatarData = null;

	static final SelectItem [] sexs = new SelectItem [] 
	          {
				new SelectItem(Sex.MALE, "Male"),
				new SelectItem(Sex.FEMALE, "Female")
	          };
	
	public void uploadAvatar(UploadEvent event) {
		UploadItem item = event.getUploadItem();
		avatarData = item.getFile();
	}
	
	//TODO nick - are we saving current user?
	public void saveUser(){
		if (avatarData != null) {
			if(!fileManager.saveAvatar(avatarData.getPath(), user)){
				Events.instance().raiseEvent(Constants.ADD_ERROR_EVENT, new Exception("File IO Error"));
				return;
			}
			avatarData.delete();
			avatarData = null;
			user.setHasAvatar(true);
		}
		user = userAction.updateUser();
		model.resetModel(NavigationEnum.ALL_SHELFS, user, model.getSelectedShelf(), model.getSelectedAlbum(), model.getSelectedImage());
	}
	
	public void cancel() {
		user = userAction.resetUser();
		avatarData = null;
		model.resetModel(NavigationEnum.ALL_SHELFS, user, model.getSelectedShelf(), model.getSelectedAlbum(), model.getSelectedImage());
	}
	
	public SelectItem [] getSexs () {
		return sexs;
	}

	public Boolean getAvatarModalOpened() {
		return avatarModalOpened;
	}

	public void setAvatarModalOpened(Boolean avatarModalOpened) {
		this.avatarModalOpened = avatarModalOpened;
	}

	public File getAvatarData() {
		return avatarData;
	}

	public void setAvatarData(File avatarData) {
		this.avatarData = avatarData;
	}
}
