MapView.java 6.01 KB
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fi.insomnia.bortal.view;

import java.math.BigDecimal;
import java.util.Map;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.insomnia.bortal.beans.EventBeanLocal;
import fi.insomnia.bortal.beans.PlaceBeanLocal;
import fi.insomnia.bortal.beans.PlaceMapBeanLocal;
import fi.insomnia.bortal.beans.UserBeanLocal;
import fi.insomnia.bortal.enums.Permission;
import fi.insomnia.bortal.enums.RolePermission;
import fi.insomnia.bortal.exceptions.BortalCatchableException;
import fi.insomnia.bortal.model.EventMap;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.Place;
import fi.insomnia.bortal.model.User;

/**
 * 
 * @author tuukka
 */
@ManagedBean(name = "mapView")
@SessionScoped
public class MapView extends GenericView {

    private Logger logger = LoggerFactory.getLogger(MapView.class);

    @EJB
    private PlaceMapBeanLocal placeMapBean;

    @EJB
    private PlaceBeanLocal placeBean;
    @EJB
    private UserBeanLocal userBean;

    @EJB
    private EventBeanLocal eventBean;

    private EventMap activeMap;

    private Place clickedplace;

    private User user;

    // private Place selectedPlace = null;

    /** Creates a new instance of MapView */
    public MapView() {
    }

    public void initSelf() {
        user = userBean.getCurrentUser();
    }

    public boolean canUserBuy() {
        if (user == null) {
            return false;
        }
        return user.getAccountBalance().compareTo(BigDecimal.ZERO) > 0;
    }

    public String buySelectedPlaces() {
        try {
            placeBean.buySelectedPlaces(getActiveMap());
        } catch (BortalCatchableException e) {
            addFaceMessage("mapView.errorWhileBuyingPlaces");
            placeBean.releaseUsersPlaces();
        }
        return "";
    }

    public BigDecimal getReservationPrice() {
        return placeBean.totalReservationPrice(activeMap, null);
    }

    public void placeSelectActionListener(ActionEvent e) {
        userBean.fatalPermission(Permission.MAP, RolePermission.EXECUTE);

        User user = userBean.getCurrentUser();

        FacesContext context = FacesContext.getCurrentInstance();
        String clientId = e.getComponent().getClientId(context);

        Map<String, String> requestParams = context.getExternalContext().getRequestParameterMap();

        int x = new Integer(requestParams.get(clientId + ".x")).intValue();
        int y = new Integer(requestParams.get(clientId + ".y")).intValue();
        logger.debug("Clicked position {} {}", x, y);

        setClickedplace(placeBean.findPlace(getActiveMap(), x, y));
        logger.debug("Clicked place: {}", getClickedplace());

        if (getClickedplace() != null) {

            if (getClickedplace().isReservedFor(user)) {
                logger.debug("Place {} was reserved for user. Removing reservation!", clickedplace);
                if (!placeBean.releasePlace(getClickedplace(), user)) {
                    this.addFaceMessage("mapView.errorWhenReleasingPlace");
                }

            } else if (getClickedplace().isBuyable() && !getClickedplace().isTaken()) {
                BigDecimal balance = userBean.getCurrentUser().getAccountBalance();
                BigDecimal price = placeBean.totalReservationPrice(getActiveMap(), getClickedplace());
                logger.debug("Balance {}, price {}", balance, price);
                if (price.compareTo(balance) <= 0) {
                    logger.debug("Place was free. Marking for user.");
                    if (!placeBean.reservePlace(getClickedplace(), user)) {
                        this.addFaceMessage("mapView.errorWhenReservingPlace");

                    }
                } else {
                    if (userBean.getCurrentUser().getAccountBalance().compareTo(BigDecimal.ZERO) > 0) {
                        addFaceMessage("mapView.notEnoughCreditsToReserve");
                    }
                    logger.debug("Did not have enought money to reserve place! required {} , got {}", price, balance);
                }
            }
        }
        logger.debug("Done calling PlaceSelectActionListener");
    }

    public String releaseUsersPlaces() {
        placeBean.releaseUsersPlaces();
        return "";
    }

    public String getSelectPlaceMapUrl() {

        EventMap map = getActiveMap();

        if (map == null) {
            return "";
        }

        // String ret = placeMapBean.getSelectPlaceMapUrl(getActiveMap(),
        // selectedPlaces, user);
        StringBuilder ret = new StringBuilder("/PlaceMap?");
        ret.append("mapid=").append(map.getId().getId());

        logger.debug("Returning placemapUrl: {}", ret.toString());
        return ret.toString();
    }

    /**
     * @return the activeMap, if it's not setted, return events first map. If
     *         this event does not have map, return null.
     */
    public EventMap getActiveMap() {
        userBean.fatalPermission(Permission.MAP, RolePermission.READ);
        setUser(userBean.getCurrentUser());
        LanEvent event = eventBean.getCurrentEvent();
        for (EventMap map : event.getEventMaps()) {
            if (map.isActive()) {
                activeMap = map;
                break;
            }
        }

        return activeMap;
    }

    /**
     * @param activeMap
     *            the activeMap to set
     */
    public void setActiveMap(EventMap activeMap) {
        this.activeMap = activeMap;
    }

    public Long placeLeftToSelect() {
        return placeMapBean.selectablePlaceCount(getActiveMap());

    }

    public void setClickedplace(Place clickedplace) {
        this.clickedplace = clickedplace;
    }

    public Place getClickedplace() {
        return clickedplace;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getUser() {

        return user;
    }
}