"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumberControlRendererTester = exports.NumberControlRenderer = void 0;
var tslib_1 = require("tslib");
/*
  The MIT License
  
  Copyright (c) 2017-2019 EclipseSource Munich
  https://github.com/eclipsesource/jsonforms
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/
var core_1 = require("@angular/core");
var angular_1 = require("@jsonforms/angular");
var core_2 = require("@jsonforms/core");
var merge_1 = tslib_1.__importDefault(require("lodash/merge"));
var NumberControlRenderer = /** @class */ (function (_super) {
    tslib_1.__extends(NumberControlRenderer, _super);
    function NumberControlRenderer(jsonformsService) {
        var _this = _super.call(this, jsonformsService) || this;
        _this.MAXIMUM_FRACTIONAL_DIGITS = 20;
        _this.getEventValue = function (event) {
            var cleanPattern = new RegExp("[^-+0-9" + _this.decimalSeparator + "]", 'g');
            var cleaned = event.target.value.replace(cleanPattern, '');
            var normalized = cleaned.replace(_this.decimalSeparator, '.');
            if (normalized === '') {
                return undefined;
            }
            // convert to number
            var number = +normalized;
            // if not a number just return the string
            if (Number.isNaN(number)) {
                return event.target.value;
            }
            return number;
        };
        _this.getValue = function () {
            if (_this.data !== undefined && _this.data !== null) {
                if (typeof _this.data === 'number') {
                    return _this.numberFormat.format(_this.data);
                }
                return _this.data;
            }
            return '';
        };
        return _this;
    }
    NumberControlRenderer.prototype.onChange = function (ev) {
        var data = this.oldValue
            ? ev.target.value.replace(this.oldValue, '')
            : ev.target.value;
        // ignore these
        if (data === '.' ||
            data === ',' ||
            data === ' ' ||
            // if the value is 0 and we already have a value then we ignore
            (data === '0' &&
                this.getValue() !== '' &&
                // a 0 in the first place
                ((ev.target.selectionStart === 1 && ev.target.selectionEnd === 1) ||
                    // or in the last place as this doesn't change the value (when there is a separator)
                    (ev.target.selectionStart === ev.target.value.length &&
                        ev.target.selectionEnd === ev.target.value.length &&
                        ev.target.value.indexOf(this.decimalSeparator) !== -1)))) {
            this.oldValue = ev.target.value;
            return;
        }
        _super.prototype.onChange.call(this, ev);
        this.oldValue = this.getValue();
    };
    NumberControlRenderer.prototype.mapAdditionalProps = function (props) {
        if (this.scopedSchema) {
            var defaultStep = core_2.isNumberControl(this.uischema, this.rootSchema)
                ? 0.1
                : 1;
            this.min = this.scopedSchema.minimum;
            this.max = this.scopedSchema.maximum;
            this.multipleOf = this.scopedSchema.multipleOf || defaultStep;
            var appliedUiSchemaOptions = merge_1.default({}, props.config, this.uischema.options);
            var currentLocale = core_2.getLocale(this.jsonFormsService.getState());
            if (this.locale === undefined || this.locale !== currentLocale) {
                this.locale = currentLocale;
                this.numberFormat = new Intl.NumberFormat(this.locale, {
                    useGrouping: appliedUiSchemaOptions.useGrouping,
                    maximumFractionDigits: this.MAXIMUM_FRACTIONAL_DIGITS
                });
                this.determineDecimalSeparator();
                this.oldValue = this.getValue();
            }
            this.form.setValue(this.getValue());
        }
    };
    NumberControlRenderer.prototype.determineDecimalSeparator = function () {
        var example = this.numberFormat.format(1.1);
        this.decimalSeparator = example.charAt(1);
    };
    NumberControlRenderer.decorators = [
        { type: core_1.Component, args: [{
                    selector: 'NumberControlRenderer',
                    template: "\n    <mat-form-field fxFlex [fxHide]=\"hidden\">\n      <mat-label>{{ label }}</mat-label>\n      <input\n        matInput\n        (input)=\"onChange($event)\"\n        [value]=\"getValue()\"\n        [id]=\"id\"\n        [formControl]=\"form\"\n        [min]=\"min\"\n        [max]=\"max\"\n        [step]=\"multipleOf\"\n      />\n      <mat-hint *ngIf=\"shouldShowUnfocusedDescription()\">{{ description }}</mat-hint>\n      <mat-error>{{ error }}</mat-error>\n    </mat-form-field>\n  ",
                    changeDetection: core_1.ChangeDetectionStrategy.OnPush
                },] }
    ];
    NumberControlRenderer.ctorParameters = function () { return [
        { type: angular_1.JsonFormsAngularService }
    ]; };
    return NumberControlRenderer;
}(angular_1.JsonFormsControl));
exports.NumberControlRenderer = NumberControlRenderer;
exports.NumberControlRendererTester = core_2.rankWith(2, core_2.or(core_2.isNumberControl, core_2.isIntegerControl));
//# sourceMappingURL=number.renderer.js.map