/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.faces.facelets.component.spinner;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;


public class NumberSpinner extends BaseSpinner {

    private int value = 0;
    private Integer min = null;
    private Integer max = null;
    private INumberSpinnerListener listener = null;

    public NumberSpinner(int number) {
        this.value = number;
    }

    public NumberSpinner(int number, Integer min, Integer max, INumberSpinnerListener spinnerListener) {
        this.value = number;
        this.listener = spinnerListener;
        this.min = min;
        this.max = max;
    }

    public NumberSpinner() {
    }

    public void incrementBtnClicked(ActionEvent evt) {
        int oldVal = value;
        int newVal = value + incrementBy;
        if (max != null && newVal > max) {
            String msg = String.format("Maximum value of %s exceeded", max);
            FacesContext.getCurrentInstance().addMessage(evt.getComponent().getClientId(), new FacesMessage(FacesMessage.SEVERITY_WARN, msg, ""));
            return;
        }
        value = newVal;
        if (listener != null) {
            listener.valueChanged(oldVal, value);
        }
    }

    public void decrementBtnClicked(ActionEvent evt) {
        int oldVal = value;
        int newVal = value - incrementBy;
        if (min != null && newVal < min) {
            String msg = String.format("Minimum value of %s exceeded", min);
            FacesContext.getCurrentInstance().addMessage(evt.getComponent().getClientId(), new FacesMessage(FacesMessage.SEVERITY_WARN, msg, ""));
            return;
        }
        value = newVal;
        if (listener != null) {
            listener.valueChanged(oldVal, value);
        }
    }

    public void setValue(int val) {
        this.value = val;
    }

    public int getValue() {
        return value;
    }

}
