import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Validators } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { getCustomFieldsDefaults, LanguageCode, Permission, TypedBaseDetailComponent, } from '@vendure/admin-ui/core';
import { gql } from 'apollo-angular';
import { switchMap, tap, withLatestFrom } from 'rxjs/operators';
import * as i0 from "@angular/core";
import * as i1 from "@vendure/admin-ui/core";
import * as i2 from "@angular/forms";
import * as i3 from "@clr/angular";
import * as i4 from "@angular/common";
import * as i5 from "@ngx-translate/core";
export const GET_GLOBAL_SETTINGS_DETAIL = gql `
    query GetGlobalSettingsDetail {
        globalSettings {
            ...GlobalSettingsDetail
        }
    }
    fragment GlobalSettingsDetail on GlobalSettings {
        id
        createdAt
        updatedAt
        availableLanguages
        trackInventory
        outOfStockThreshold
    }
`;
export class GlobalSettingsComponent extends TypedBaseDetailComponent {
    constructor(changeDetector, dataService, formBuilder, notificationService) {
        super();
        this.changeDetector = changeDetector;
        this.dataService = dataService;
        this.formBuilder = formBuilder;
        this.notificationService = notificationService;
        this.customFields = this.getCustomFieldConfig('GlobalSettings');
        this.detailForm = this.formBuilder.group({
            availableLanguages: [[]],
            trackInventory: false,
            outOfStockThreshold: [0, Validators.required],
            customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)),
        });
        this.languageCodes = Object.values(LanguageCode);
        this.updatePermission = [Permission.UpdateSettings, Permission.UpdateGlobalSettings];
    }
    ngOnInit() {
        this.init();
        this.dataService.client.userStatus().single$.subscribe(({ userStatus }) => {
            if (!userStatus.permissions.includes(Permission.UpdateSettings)) {
                const languagesSelect = this.detailForm.get('availableLanguages');
                if (languagesSelect) {
                    languagesSelect.disable();
                }
            }
        });
    }
    ngOnDestroy() {
        this.destroy();
    }
    save() {
        if (!this.detailForm.dirty) {
            return;
        }
        this.dataService.settings
            .updateGlobalSettings(this.detailForm.value)
            .pipe(tap(({ updateGlobalSettings }) => {
            switch (updateGlobalSettings.__typename) {
                case 'GlobalSettings':
                    this.detailForm.markAsPristine();
                    this.changeDetector.markForCheck();
                    this.notificationService.success(_('common.notify-update-success'), {
                        entity: 'Settings',
                    });
                    break;
                case 'ChannelDefaultLanguageError':
                    this.notificationService.error(updateGlobalSettings.message);
            }
        }), switchMap(() => this.serverConfigService.refreshGlobalSettings()), withLatestFrom(this.dataService.client.uiState().single$))
            .subscribe(([{ globalSettings }, { uiState }]) => {
            const availableLangs = globalSettings.availableLanguages;
            if (availableLangs.length && !availableLangs.includes(uiState.contentLanguage)) {
                this.dataService.client.setContentLanguage(availableLangs[0]).subscribe();
            }
        });
    }
    setFormValues(entity, languageCode) {
        this.detailForm.patchValue({
            availableLanguages: entity.availableLanguages,
            trackInventory: entity.trackInventory,
            outOfStockThreshold: entity.outOfStockThreshold,
        });
        if (this.customFields.length) {
            this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.2", ngImport: i0, type: GlobalSettingsComponent, deps: [{ token: i0.ChangeDetectorRef }, { token: i1.DataService }, { token: i2.FormBuilder }, { token: i1.NotificationService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.2.2", type: GlobalSettingsComponent, selector: "vdr-global-settings", usesInheritance: true, ngImport: i0, template: "<vdr-page-block>\n    <vdr-action-bar>\n        <vdr-ab-right>\n            <vdr-action-bar-items locationId=\"global-settings-detail\"></vdr-action-bar-items>\n            <button\n                class=\"btn btn-primary\"\n                (click)=\"save()\"\n                *vdrIfPermissions=\"updatePermission\"\n                [disabled]=\"detailForm.invalid || detailForm.pristine\"\n            >\n                {{ 'common.update' | translate }}\n            </button>\n        </vdr-ab-right>\n    </vdr-action-bar>\n</vdr-page-block>\n\n<form class=\"form\" [formGroup]=\"detailForm\">\n    <vdr-page-block>\n        <vdr-card>\n            <div class=\"form-grid\">\n                <vdr-form-field\n                    [label]=\"'common.available-languages' | translate\"\n                    for=\"availableLanguages\"\n                    [tooltip]=\"'settings.global-available-languages-tooltip' | translate\"\n                >\n                    <vdr-language-code-selector\n                        formControlName=\"availableLanguages\"\n                        [languageCodes]=\"languageCodes\"\n                    ></vdr-language-code-selector>\n                </vdr-form-field>\n                <vdr-form-field\n                    [label]=\"'settings.global-out-of-stock-threshold' | translate\"\n                    for=\"outOfStockThreshold\"\n                    [tooltip]=\"'settings.global-out-of-stock-threshold-tooltip' | translate\"\n                >\n                    <input\n                        id=\"outOfStockThreshold\"\n                        type=\"number\"\n                        formControlName=\"outOfStockThreshold\"\n                        [readonly]=\"!(updatePermission | hasPermission)\"\n                    />\n                </vdr-form-field>\n                <vdr-form-field\n                    [label]=\"'settings.track-inventory-default' | translate\"\n                    for=\"enabled\"\n                    [tooltip]=\"'catalog.track-inventory-tooltip' | translate\"\n                >\n                    <clr-toggle-wrapper>\n                        <input\n                            type=\"checkbox\"\n                            clrToggle\n                            name=\"enabled\"\n                            formControlName=\"trackInventory\"\n                            [vdrDisabled]=\"!(updatePermission | hasPermission)\"\n                        />\n                    </clr-toggle-wrapper>\n                </vdr-form-field>\n            </div>\n        </vdr-card>\n        <vdr-card\n            formGroupName=\"customFields\"\n            *ngIf=\"customFields.length\"\n            [title]=\"'common.custom-fields' | translate\"\n        >\n            <vdr-tabbed-custom-fields\n                entityName=\"GlobalSettings\"\n                [customFields]=\"customFields\"\n                [customFieldsFormGroup]=\"detailForm.get('customFields')\"\n                [readonly]=\"!(updatePermission | hasPermission)\"\n            ></vdr-tabbed-custom-fields>\n        </vdr-card>\n\n        <vdr-custom-detail-component-host\n            locationId=\"global-settings-detail\"\n            [entity$]=\"entity$\"\n            [detailForm]=\"detailForm\"\n        ></vdr-custom-detail-component-host>\n    </vdr-page-block>\n</form>\n", styles: ["::ng-deep ng-select .ng-value>span{margin:0!important}::ng-deep ng-select .ng-arrow-wrapper .ng-arrow{margin:0!important}::ng-deep ng-select .ng-select-container>span{margin:0!important}\n"], dependencies: [{ kind: "directive", type: i3.ClrCheckbox, selector: "[clrCheckbox],[clrToggle]" }, { kind: "component", type: i3.ClrCheckboxWrapper, selector: "clr-checkbox-wrapper,clr-toggle-wrapper" }, { kind: "directive", type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i2.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i2.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2.NumberValueAccessor, selector: "input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]" }, { kind: "directive", type: i2.CheckboxControlValueAccessor, selector: "input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]" }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i2.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i2.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "directive", type: i2.FormGroupName, selector: "[formGroupName]", inputs: ["formGroupName"] }, { kind: "component", type: i1.ActionBarComponent, selector: "vdr-action-bar" }, { kind: "component", type: i1.ActionBarRightComponent, selector: "vdr-ab-right", inputs: ["grow"] }, { kind: "component", type: i1.FormFieldComponent, selector: "vdr-form-field", inputs: ["label", "for", "tooltip", "errors", "readOnlyToggle"] }, { kind: "directive", type: i1.FormFieldControlDirective, selector: "input, textarea, select" }, { kind: "directive", type: i1.IfPermissionsDirective, selector: "[vdrIfPermissions]", inputs: ["vdrIfPermissions", "vdrIfPermissionsElse"] }, { kind: "component", type: i1.ActionBarItemsComponent, selector: "vdr-action-bar-items", inputs: ["locationId"] }, { kind: "directive", type: i1.DisabledDirective, selector: "[vdrDisabled]", inputs: ["vdrDisabled"] }, { kind: "component", type: i1.TabbedCustomFieldsComponent, selector: "vdr-tabbed-custom-fields", inputs: ["entityName", "customFields", "customFieldsFormGroup", "readonly", "compact", "showLabel"] }, { kind: "component", type: i1.CustomDetailComponentHostComponent, selector: "vdr-custom-detail-component-host", inputs: ["locationId", "entity$", "detailForm"] }, { kind: "component", type: i1.PageBlockComponent, selector: "vdr-page-block" }, { kind: "component", type: i1.CardComponent, selector: "vdr-card", inputs: ["title", "paddingX"] }, { kind: "component", type: i1.LanguageCodeSelectorComponent, selector: "vdr-language-code-selector", inputs: ["languageCodes"] }, { kind: "pipe", type: i5.TranslatePipe, name: "translate" }, { kind: "pipe", type: i1.HasPermissionPipe, name: "hasPermission" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.2", ngImport: i0, type: GlobalSettingsComponent, decorators: [{
            type: Component,
            args: [{ selector: 'vdr-global-settings', changeDetection: ChangeDetectionStrategy.OnPush, template: "<vdr-page-block>\n    <vdr-action-bar>\n        <vdr-ab-right>\n            <vdr-action-bar-items locationId=\"global-settings-detail\"></vdr-action-bar-items>\n            <button\n                class=\"btn btn-primary\"\n                (click)=\"save()\"\n                *vdrIfPermissions=\"updatePermission\"\n                [disabled]=\"detailForm.invalid || detailForm.pristine\"\n            >\n                {{ 'common.update' | translate }}\n            </button>\n        </vdr-ab-right>\n    </vdr-action-bar>\n</vdr-page-block>\n\n<form class=\"form\" [formGroup]=\"detailForm\">\n    <vdr-page-block>\n        <vdr-card>\n            <div class=\"form-grid\">\n                <vdr-form-field\n                    [label]=\"'common.available-languages' | translate\"\n                    for=\"availableLanguages\"\n                    [tooltip]=\"'settings.global-available-languages-tooltip' | translate\"\n                >\n                    <vdr-language-code-selector\n                        formControlName=\"availableLanguages\"\n                        [languageCodes]=\"languageCodes\"\n                    ></vdr-language-code-selector>\n                </vdr-form-field>\n                <vdr-form-field\n                    [label]=\"'settings.global-out-of-stock-threshold' | translate\"\n                    for=\"outOfStockThreshold\"\n                    [tooltip]=\"'settings.global-out-of-stock-threshold-tooltip' | translate\"\n                >\n                    <input\n                        id=\"outOfStockThreshold\"\n                        type=\"number\"\n                        formControlName=\"outOfStockThreshold\"\n                        [readonly]=\"!(updatePermission | hasPermission)\"\n                    />\n                </vdr-form-field>\n                <vdr-form-field\n                    [label]=\"'settings.track-inventory-default' | translate\"\n                    for=\"enabled\"\n                    [tooltip]=\"'catalog.track-inventory-tooltip' | translate\"\n                >\n                    <clr-toggle-wrapper>\n                        <input\n                            type=\"checkbox\"\n                            clrToggle\n                            name=\"enabled\"\n                            formControlName=\"trackInventory\"\n                            [vdrDisabled]=\"!(updatePermission | hasPermission)\"\n                        />\n                    </clr-toggle-wrapper>\n                </vdr-form-field>\n            </div>\n        </vdr-card>\n        <vdr-card\n            formGroupName=\"customFields\"\n            *ngIf=\"customFields.length\"\n            [title]=\"'common.custom-fields' | translate\"\n        >\n            <vdr-tabbed-custom-fields\n                entityName=\"GlobalSettings\"\n                [customFields]=\"customFields\"\n                [customFieldsFormGroup]=\"detailForm.get('customFields')\"\n                [readonly]=\"!(updatePermission | hasPermission)\"\n            ></vdr-tabbed-custom-fields>\n        </vdr-card>\n\n        <vdr-custom-detail-component-host\n            locationId=\"global-settings-detail\"\n            [entity$]=\"entity$\"\n            [detailForm]=\"detailForm\"\n        ></vdr-custom-detail-component-host>\n    </vdr-page-block>\n</form>\n", styles: ["::ng-deep ng-select .ng-value>span{margin:0!important}::ng-deep ng-select .ng-arrow-wrapper .ng-arrow{margin:0!important}::ng-deep ng-select .ng-select-container>span{margin:0!important}\n"] }]
        }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i1.DataService }, { type: i2.FormBuilder }, { type: i1.NotificationService }]; } });
//# sourceMappingURL=data:application/json;base64, 