// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

/**
 * This field is basically a simple ExtJS text field with some constraints to handle
 * weights as its value. That is, only digits, dots and commas are valid input characters
 * and a value can't have more than 3 decimal places. Furthermore the return value of the
 * getSubmitData method, which is used when saving ExtJS forms, returns a object with a float as
 * the value associated with the name of this field.
 */
Ext.define('Shopware.apps.ViisonShippingCommonOrder.view.WeightField', {

    /**
     * Extend from the standard ExtJS 4.
     */
    extend: 'Ext.form.field.Text',

    /**
     * The short alias for this class.
     */
    alias: 'widget.x-custom-field-weight',

    /**
     * A regular expression limiting the allowed input characters for this field.
     */
    maskRe: new RegExp('[\\d\\.,]'),

    /**
     * The default value which will be returned by the getSubmitData method if the content
     * of this field is no parsable float (e.g. an empty text).
     */
    defaultSubmitValue: null,

    initComponent: function() {
        // Allow only empty or decimal values with at most 3 decimal places
        this.on('change', function(field, newValue, oldValue) {
//{literal}
            var matcher = new RegExp('^\\d+((\\.|,)\\d{0,3})?$', 'i');
//{/literal}
            if (!matcher.test(newValue) && newValue.length > 0) {
                field.setValue(oldValue);
            }
        });

        this.callParent(arguments);
    },

    /**
     * Override the default getSubmitValue method to convert the value of this field to a float.
     *
     * @return float The parsed float of this field's value.
     */
    getSubmitValue: function() {
        var value = ((typeof this.value == 'string') ? parseFloat(this.value.replace(',', '.')) : this.value);
        return value || this.defaultSubmitValue;
    },

    /**
     * Display comma as decimal separator to the user
     */
    setValue: function(value) {
        if (value != null) {
            value = value.toString().replace('.', ',');
        }
        this.callParent(arguments);
    }

});
