import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { EventEmitter, Attribute, Self, Optional, Input, Output, Component, ViewEncapsulation, isDevMode, NgZone, ChangeDetectorRef, ContentChildren, ChangeDetectionStrategy, NgModule } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subject, defer, merge } from 'rxjs';
import { take, switchMap, startWith, takeUntil } from 'rxjs/operators';
import { NtFormFieldControl } from '@ng-tangram/components/forms';
import { CommonModule } from '@angular/common';

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var uniqueId = 0;
var NtRadioChange = (function () {
    function NtRadioChange(source, selected) {
        this.source = source;
        this.selected = selected;
    }
    return NtRadioChange;
}());
var NtRadioComponent = (function () {
    function NtRadioComponent(tabIndex, ngControl) {
        this.ngControl = ngControl;
        this.id = "nt-radio-" + uniqueId++;
        this._disabled = false;
        this._readonly = false;
        this._checked = false;
        this._name = this.id;
        this.change = new EventEmitter();
        this._onChange = function () { };
        this._onTouched = function () { };
        if (this.ngControl) {
            this.ngControl.valueAccessor = this;
        }
        this.tabIndex = parseInt(tabIndex) || 0;
    }
    Object.defineProperty(NtRadioComponent.prototype, "value", {
        get: function () { return this._value; },
        set: function (value) { this._value = value; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioComponent.prototype, "disabled", {
        get: function () { return this._disabled; },
        set: function (value) { this._disabled = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioComponent.prototype, "readonly", {
        get: function () { return this._readonly; },
        set: function (value) { this._readonly = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioComponent.prototype, "checked", {
        get: function () { return this._checked; },
        set: function (value) { this._checked = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioComponent.prototype, "name", {
        get: function () { return this._name; },
        set: function (value) { this._name = value; },
        enumerable: true,
        configurable: true
    });
    NtRadioComponent.prototype.writeValue = function (value) {
        this._checked = !!value;
    };
    NtRadioComponent.prototype.registerOnChange = function (fn) {
        this._onChange = fn;
    };
    NtRadioComponent.prototype.registerOnTouched = function (fn) {
        this._onTouched = fn;
    };
    NtRadioComponent.prototype.setDisabledState = function (isDisabled) {
        this.disabled = isDisabled;
    };
    NtRadioComponent.prototype._onInputClick = function (event) {
        event.stopPropagation();
    };
    NtRadioComponent.prototype._onInputChange = function (event) {
        event.stopPropagation();
        this._checked = true;
        this._emitChangeEvent();
    };
    NtRadioComponent.prototype._emitChangeEvent = function () {
        var event = new NtRadioChange(this, this.checked);
        this._onChange(this.checked);
        this._onTouched();
        this.change.emit(event);
    };
    NtRadioComponent.ctorParameters = function () { return [
        { type: String, decorators: [{ type: Attribute, args: ['tabindex',] }] },
        { type: NgControl, decorators: [{ type: Self }, { type: Optional }] }
    ]; };
    __decorate([
        Input()
    ], NtRadioComponent.prototype, "value", null);
    __decorate([
        Input()
    ], NtRadioComponent.prototype, "disabled", null);
    __decorate([
        Input()
    ], NtRadioComponent.prototype, "readonly", null);
    __decorate([
        Input()
    ], NtRadioComponent.prototype, "checked", null);
    __decorate([
        Input()
    ], NtRadioComponent.prototype, "name", null);
    __decorate([
        Output()
    ], NtRadioComponent.prototype, "change", void 0);
    NtRadioComponent = __decorate([
        Component({
            selector: 'nt-radio',
            encapsulation: ViewEncapsulation.None,
            template: "<label class=\"nt-radio-layout\">\n  <div class=\"nt-radio-input-container\">\n    <input class=\"cdk-visually-hidden\"\n      type=\"radio\"\n      [name]=\"name\"\n      [tabIndex]=\"tabIndex\"\n      [disabled]=\"disabled\"\n      [checked]=\"checked\"\n      (change)=\"_onInputChange($event)\"\n      (click)=\"_onInputClick($event)\">\n    <div class=\"nt-radio-input\"></div>\n  </div>\n  <span class=\"nt-radio-label\">\n    <ng-content></ng-content>\n  </span>\n</label>\n",
            host: {
                'class': 'nt-radio',
                '[class.nt-radio-disabled]': 'disabled'
            }
        }),
        __param(0, Attribute('tabindex')),
        __param(1, Self()), __param(1, Optional())
    ], NtRadioComponent);
    return NtRadioComponent;
}());

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate$1 = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1 = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
function getNtRdioGroupNonFunctionValueError() {
    return Error('`compareWith` must be a function.');
}
var uniqueId$1 = 0;
var NtRadioGroupComponent = (function (_super) {
    __extends(NtRadioGroupComponent, _super);
    function NtRadioGroupComponent(_ngZone, _changeDetectorRef, ngControl) {
        var _this = _super.call(this) || this;
        _this._ngZone = _ngZone;
        _this._changeDetectorRef = _changeDetectorRef;
        _this.ngControl = ngControl;
        _this.id = "nt-radio-group-" + uniqueId$1++;
        _this._destroy = new Subject();
        _this._disabled = false;
        _this._readonly = false;
        _this._required = false;
        _this._name = _this.id;
        _this._compareWith = function (o1, o2) { return o1 === o2; };
        _this.checkedChanges = defer(function () {
            if (_this.radios) {
                return merge.apply(void 0, __spread(_this.radios.map(function (item) { return item.change; })));
            }
            return _this._ngZone.onStable
                .asObservable()
                .pipe(take(1), switchMap(function () { return _this.checkedChanges; }));
        });
        _this._onChange = function () { };
        _this._onTouched = function () { };
        if (_this.ngControl) {
            _this.ngControl.valueAccessor = _this;
        }
        return _this;
    }
    NtRadioGroupComponent_1 = NtRadioGroupComponent;
    Object.defineProperty(NtRadioGroupComponent.prototype, "value", {
        get: function () { return this._value; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioGroupComponent.prototype, "disabled", {
        get: function () { return this._disabled; },
        set: function (value) { this._disabled = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioGroupComponent.prototype, "required", {
        get: function () { return this._required; },
        set: function (value) { this._required = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioGroupComponent.prototype, "readonly", {
        get: function () { return this._readonly; },
        set: function (value) { this._readonly = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioGroupComponent.prototype, "name", {
        get: function () { return this._name; },
        set: function (value) {
            this._name = value;
            this._updateRadioButtonNames();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtRadioGroupComponent.prototype, "compareWith", {
        set: function (fn) {
            if (typeof fn !== 'function') {
                throw getNtRdioGroupNonFunctionValueError();
            }
            else {
                this._compareWith = fn;
            }
        },
        enumerable: true,
        configurable: true
    });
    NtRadioGroupComponent.prototype.ngAfterViewInit = function () {
        var _this = this;
        this.radios.changes.pipe(startWith(null), takeUntil(this._destroy)).subscribe(function () {
            _this._resetRadios();
            _this._initializeChecked();
        });
    };
    NtRadioGroupComponent.prototype.ngOnDestroy = function () {
        this._destroy.next();
        this._destroy.complete();
    };
    NtRadioGroupComponent.prototype.writeValue = function (value) {
        if (this.radios) {
            this._setCheckedByValue(value);
        }
    };
    NtRadioGroupComponent.prototype.registerOnChange = function (fn) {
        this._onChange = fn;
    };
    NtRadioGroupComponent.prototype.registerOnTouched = function (fn) {
        this._onTouched = fn;
    };
    NtRadioGroupComponent.prototype.focus = function () {
        if (!this.disabled) {
            this._onTouched();
        }
    };
    NtRadioGroupComponent.prototype._initializeChecked = function () {
        var _this = this;
        Promise.resolve().then(function () {
            _this._updateRadioButtonNames();
            _this._setCheckedByValue(_this.ngControl ? _this.ngControl.value : _this.value);
        });
    };
    NtRadioGroupComponent.prototype._resetRadios = function () {
        var _this = this;
        var changedOrDestroyed = merge(this.radios.changes, this._destroy);
        this.checkedChanges.pipe(takeUntil(changedOrDestroyed)).subscribe(function (change) {
            _this._setValues(change.source);
        });
        merge.apply(void 0, __spread(this.radios.map(function (item) { return item.change; }))).pipe(takeUntil(changedOrDestroyed))
            .subscribe(function () {
            _this._changeDetectorRef.markForCheck();
        });
    };
    NtRadioGroupComponent.prototype._setCheckedByValue = function (value) {
        this._value = value;
        this.radios.forEach(function (item) { return item.checked = false; });
        this._checkedValue(value);
        this._changeDetectorRef.markForCheck();
    };
    NtRadioGroupComponent.prototype._checkedValue = function (value) {
        var _this = this;
        var correspondingItem = this.radios.find(function (item) {
            try {
                return item.value != null && _this._compareWith(item.value, value);
            }
            catch (error) {
                if (isDevMode()) {
                    console.warn(error);
                }
                return false;
            }
        });
        if (correspondingItem) {
            correspondingItem.checked = true;
        }
        return correspondingItem;
    };
    NtRadioGroupComponent.prototype._setValues = function (radio) {
        this._value = radio.value;
        this._onChange(this._value);
        this._onTouched();
        this._changeDetectorRef.markForCheck();
    };
    NtRadioGroupComponent.prototype._updateRadioButtonNames = function () {
        var _this = this;
        if (this.radios) {
            this.radios.forEach(function (radio) {
                radio.name = _this.name;
            });
        }
    };
    var NtRadioGroupComponent_1;
    NtRadioGroupComponent.ctorParameters = function () { return [
        { type: NgZone },
        { type: ChangeDetectorRef },
        { type: NgControl, decorators: [{ type: Self }, { type: Optional }] }
    ]; };
    __decorate$1([
        Input()
    ], NtRadioGroupComponent.prototype, "disabled", null);
    __decorate$1([
        Input()
    ], NtRadioGroupComponent.prototype, "required", null);
    __decorate$1([
        Input()
    ], NtRadioGroupComponent.prototype, "readonly", null);
    __decorate$1([
        Input()
    ], NtRadioGroupComponent.prototype, "name", null);
    __decorate$1([
        ContentChildren(NtRadioComponent)
    ], NtRadioGroupComponent.prototype, "radios", void 0);
    __decorate$1([
        Input()
    ], NtRadioGroupComponent.prototype, "compareWith", null);
    NtRadioGroupComponent = NtRadioGroupComponent_1 = __decorate$1([
        Component({
            selector: 'nt-radio-group',
            template: '<ng-content></ng-content>',
            encapsulation: ViewEncapsulation.None,
            changeDetection: ChangeDetectionStrategy.OnPush,
            providers: [
                { provide: NtFormFieldControl, useExisting: NtRadioGroupComponent_1 }
            ],
            host: {
                'class': 'nt-radio-group'
            }
        }),
        __param$1(2, Self()), __param$1(2, Optional())
    ], NtRadioGroupComponent);
    return NtRadioGroupComponent;
}(NtFormFieldControl));

var __decorate$2 = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var NtRadioModule = (function () {
    function NtRadioModule() {
    }
    NtRadioModule = __decorate$2([
        NgModule({
            imports: [CommonModule],
            exports: [NtRadioComponent, NtRadioGroupComponent],
            declarations: [NtRadioComponent, NtRadioGroupComponent],
        })
    ], NtRadioModule);
    return NtRadioModule;
}());

export { NtRadioChange, NtRadioComponent, NtRadioGroupComponent, NtRadioModule, getNtRdioGroupNonFunctionValueError };
//# sourceMappingURL=radio.js.map
