import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { EventEmitter, ChangeDetectorRef, Attribute, Self, Optional, Input, Output, Component, ViewEncapsulation, ChangeDetectionStrategy, isDevMode, NgZone, ContentChildren, 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 NtCheckboxChange = (function () {
    function NtCheckboxChange(source, checked) {
        this.source = source;
        this.checked = checked;
    }
    return NtCheckboxChange;
}());
var NtCheckboxComponent = (function () {
    function NtCheckboxComponent(_changeDetectorRef, tabIndex, ngControl) {
        this._changeDetectorRef = _changeDetectorRef;
        this.ngControl = ngControl;
        this.id = "nt-checkbox-" + uniqueId++;
        this._disabled = false;
        this._readonly = false;
        this._checked = false;
        this._indeterminate = false;
        this.change = new EventEmitter();
        this.indeterminateChange = new EventEmitter();
        this._onChange = function () { };
        this._onTouched = function () { };
        if (this.ngControl) {
            this.ngControl.valueAccessor = this;
        }
        this.tabIndex = parseInt(tabIndex) || 0;
    }
    Object.defineProperty(NtCheckboxComponent.prototype, "value", {
        get: function () { return this._value; },
        set: function (value) { this._value = value; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxComponent.prototype, "disabled", {
        get: function () { return this._disabled; },
        set: function (value) {
            if (value !== this.disabled) {
                this._disabled = coerceBooleanProperty(value);
                this._changeDetectorRef.markForCheck();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxComponent.prototype, "readonly", {
        get: function () { return this._readonly; },
        set: function (value) { this._readonly = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxComponent.prototype, "checked", {
        get: function () { return this._checked; },
        set: function (value) {
            if (value !== this.checked) {
                this._checked = coerceBooleanProperty(value);
                this._changeDetectorRef.markForCheck();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxComponent.prototype, "indeterminate", {
        get: function () { return this._indeterminate; },
        set: function (value) {
            var changed = value !== this._indeterminate;
            this._indeterminate = value;
            if (changed) {
                this.indeterminateChange.emit(this._indeterminate);
            }
        },
        enumerable: true,
        configurable: true
    });
    NtCheckboxComponent.prototype.writeValue = function (value) {
        this._checked = !!value;
    };
    NtCheckboxComponent.prototype.registerOnChange = function (fn) {
        this._onChange = fn;
    };
    NtCheckboxComponent.prototype.registerOnTouched = function (fn) {
        this._onTouched = fn;
    };
    NtCheckboxComponent.prototype.setDisabledState = function (isDisabled) {
        this.disabled = isDisabled;
    };
    NtCheckboxComponent.prototype._onInputClick = function (event) {
        event.stopPropagation();
        if (!this.disabled) {
            this._checked = !this._checked;
            this._onTouched();
            this._emitChangeEvent();
        }
    };
    NtCheckboxComponent.prototype._onInteractionEvent = function (event) {
        event.stopPropagation();
    };
    NtCheckboxComponent.prototype._emitChangeEvent = function () {
        var event = new NtCheckboxChange(this, this.checked);
        this._onChange(this.checked);
        this.change.emit(event);
    };
    NtCheckboxComponent.ctorParameters = function () { return [
        { type: ChangeDetectorRef },
        { type: String, decorators: [{ type: Attribute, args: ['tabindex',] }] },
        { type: NgControl, decorators: [{ type: Self }, { type: Optional }] }
    ]; };
    __decorate([
        Input()
    ], NtCheckboxComponent.prototype, "value", null);
    __decorate([
        Input()
    ], NtCheckboxComponent.prototype, "disabled", null);
    __decorate([
        Input()
    ], NtCheckboxComponent.prototype, "readonly", null);
    __decorate([
        Input()
    ], NtCheckboxComponent.prototype, "checked", null);
    __decorate([
        Input()
    ], NtCheckboxComponent.prototype, "indeterminate", null);
    __decorate([
        Output()
    ], NtCheckboxComponent.prototype, "change", void 0);
    __decorate([
        Output()
    ], NtCheckboxComponent.prototype, "indeterminateChange", void 0);
    NtCheckboxComponent = __decorate([
        Component({
            selector: 'nt-checkbox',
            encapsulation: ViewEncapsulation.None,
            changeDetection: ChangeDetectionStrategy.OnPush,
            template: "<label class=\"nt-checkbox-layout\">\n  <div class=\"nt-checkbox-input-container\">\n    <input class=\"cdk-visually-hidden\"\n      type=\"checkbox\"\n      [tabIndex]=\"tabIndex\"\n      [checked]=\"checked\"\n      [disabled]=\"disabled\"\n      [readonly]=\"readonly\"\n      (change)=\"_onInteractionEvent($event)\"\n      (click)=\"_onInputClick($event)\">\n    <div class=\"nt-checkbox-input nt-form-control\"></div>\n  </div>\n  <span class=\"nt-checkbox-label\">\n    <ng-content></ng-content>\n  </span>\n</label>\n",
            host: {
                'class': 'nt-checkbox',
                '[class.nt-checkbox-checked]': 'checked',
                '[class.nt-checkbox-disabled]': 'disabled',
                '[class.nt-checkbox-indeterminate]': 'indeterminate',
            }
        }),
        __param(1, Attribute('tabindex')),
        __param(2, Self()), __param(2, Optional())
    ], NtCheckboxComponent);
    return NtCheckboxComponent;
}());

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 getNtCheckboxGroupNonFunctionValueError() {
    return Error('`compareWith` must be a function.');
}
var uniqueId$1 = 0;
var NtCheckboxGroupComponent = (function (_super) {
    __extends(NtCheckboxGroupComponent, _super);
    function NtCheckboxGroupComponent(_ngZone, _changeDetectorRef, ngControl) {
        var _this = _super.call(this) || this;
        _this._ngZone = _ngZone;
        _this._changeDetectorRef = _changeDetectorRef;
        _this.ngControl = ngControl;
        _this.id = "nt-checkbox-group-" + uniqueId$1++;
        _this._destroy = new Subject();
        _this._disabled = false;
        _this._readonly = false;
        _this._required = false;
        _this._compareWith = function (o1, o2) { return o1 === o2; };
        _this.checkedChanges = defer(function () {
            if (_this.checkboxes) {
                return merge.apply(void 0, __spread(_this.checkboxes.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;
    }
    NtCheckboxGroupComponent_1 = NtCheckboxGroupComponent;
    Object.defineProperty(NtCheckboxGroupComponent.prototype, "value", {
        get: function () { return this._value; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxGroupComponent.prototype, "disabled", {
        get: function () { return this._disabled; },
        set: function (value) { this._disabled = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxGroupComponent.prototype, "required", {
        get: function () { return this._required; },
        set: function (value) { this._required = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxGroupComponent.prototype, "readonly", {
        get: function () { return this._readonly; },
        set: function (value) { this._readonly = coerceBooleanProperty(value); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NtCheckboxGroupComponent.prototype, "compareWith", {
        set: function (fn) {
            if (typeof fn !== 'function') {
                throw getNtCheckboxGroupNonFunctionValueError();
            }
            else {
                this._compareWith = fn;
            }
        },
        enumerable: true,
        configurable: true
    });
    NtCheckboxGroupComponent.prototype.ngAfterViewInit = function () {
        var _this = this;
        this.checkboxes.changes.pipe(startWith(null), takeUntil(this._destroy)).subscribe(function () {
            _this._resetCheckboxs();
            _this._initializeChecked();
        });
    };
    NtCheckboxGroupComponent.prototype.ngOnDestroy = function () {
        this._destroy.next();
        this._destroy.complete();
    };
    NtCheckboxGroupComponent.prototype.writeValue = function (value) {
        if (this.checkboxes) {
            this._setCheckedByValue(value);
        }
    };
    NtCheckboxGroupComponent.prototype.registerOnChange = function (fn) {
        this._onChange = fn;
    };
    NtCheckboxGroupComponent.prototype.registerOnTouched = function (fn) {
        this._onTouched = fn;
    };
    NtCheckboxGroupComponent.prototype.focus = function () {
        if (!this.disabled) {
            this._onTouched();
        }
    };
    NtCheckboxGroupComponent.prototype._initializeChecked = function () {
        var _this = this;
        Promise.resolve().then(function () {
            _this._setCheckedByValue(_this.ngControl ? _this.ngControl.value : _this.value);
        });
    };
    NtCheckboxGroupComponent.prototype._resetCheckboxs = function () {
        var _this = this;
        var changedOrDestroyed = merge(this.checkboxes.changes, this._destroy);
        this.checkedChanges.pipe(takeUntil(changedOrDestroyed)).subscribe(function () {
            _this._setValues();
        });
        merge.apply(void 0, __spread(this.checkboxes.map(function (item) { return item.change; }))).pipe(takeUntil(changedOrDestroyed))
            .subscribe(function () {
            _this._changeDetectorRef.markForCheck();
        });
    };
    NtCheckboxGroupComponent.prototype._setCheckedByValue = function (value) {
        var _this = this;
        if (value) {
            this._value = value;
            this.checkboxes.forEach(function (item) { return item.checked = false; });
            value.forEach(function (val) { return _this._checkedValue(val); });
            this._changeDetectorRef.markForCheck();
        }
    };
    NtCheckboxGroupComponent.prototype._checkedValue = function (value) {
        var _this = this;
        var correspondingItem = this.checkboxes.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;
    };
    NtCheckboxGroupComponent.prototype._setValues = function () {
        var _this = this;
        this._value = [];
        this.checkboxes.forEach(function (item) {
            if (item.checked && !!item.value) {
                _this._value.push(item.value);
            }
        });
        this._onChange(this._value);
        this._onTouched();
        this._changeDetectorRef.markForCheck();
    };
    var NtCheckboxGroupComponent_1;
    NtCheckboxGroupComponent.ctorParameters = function () { return [
        { type: NgZone },
        { type: ChangeDetectorRef },
        { type: NgControl, decorators: [{ type: Self }, { type: Optional }] }
    ]; };
    __decorate$1([
        Input()
    ], NtCheckboxGroupComponent.prototype, "disabled", null);
    __decorate$1([
        Input()
    ], NtCheckboxGroupComponent.prototype, "required", null);
    __decorate$1([
        Input()
    ], NtCheckboxGroupComponent.prototype, "readonly", null);
    __decorate$1([
        ContentChildren(NtCheckboxComponent)
    ], NtCheckboxGroupComponent.prototype, "checkboxes", void 0);
    __decorate$1([
        Input()
    ], NtCheckboxGroupComponent.prototype, "compareWith", null);
    __decorate$1([
        Output()
    ], NtCheckboxGroupComponent.prototype, "checkedChanges", void 0);
    NtCheckboxGroupComponent = NtCheckboxGroupComponent_1 = __decorate$1([
        Component({
            selector: 'nt-checkbox-group',
            template: '<ng-content></ng-content>',
            encapsulation: ViewEncapsulation.None,
            changeDetection: ChangeDetectionStrategy.OnPush,
            providers: [
                { provide: NtFormFieldControl, useExisting: NtCheckboxGroupComponent_1 }
            ],
            host: {
                'class': 'nt-checkbox-group'
            }
        }),
        __param$1(2, Self()), __param$1(2, Optional())
    ], NtCheckboxGroupComponent);
    return NtCheckboxGroupComponent;
}(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 NtCheckboxModule = (function () {
    function NtCheckboxModule() {
    }
    NtCheckboxModule = __decorate$2([
        NgModule({
            imports: [CommonModule],
            exports: [NtCheckboxComponent, NtCheckboxGroupComponent],
            declarations: [NtCheckboxComponent, NtCheckboxGroupComponent],
        })
    ], NtCheckboxModule);
    return NtCheckboxModule;
}());

export { NtCheckboxChange, NtCheckboxComponent, NtCheckboxGroupComponent, NtCheckboxModule, getNtCheckboxGroupNonFunctionValueError };
//# sourceMappingURL=checkbox.js.map
