import {Component} from '@angular/core';

import {
    CardRowParams,
    GlobalModalsService,
    NotificationService,
    PluginSupportService,
    PrimitiveValueCardRow
} from 'm2-core';
import {CdDemoComponent} from '../../../abstract/CdDemoComponent';
import {CD_PLUGIN_NAME} from '../../../../../config';


@Component({
    template: `
        <section class="cd-content-section">
            <h4 i18n>Чтение настоек расширения</h4>

            <div class="mt-3">
                <button class="sdi-btn outlined" (click)="onGetPluginSettingsSyncClick()">
                    Прочитать синхронно
                </button>
            </div>

            <cd-code *ngIf="pluginSettings$ | async as pluginSettings"
                     langCode="ts"
            >{{pluginSettings | json}}</cd-code>
        </section>


        <section class="cd-content-section">
            <h4 i18n>Чтение пользовательских настоек для расширения</h4>

            <div class="mt-3">
                <button class="sdi-btn outlined" (click)="onSetUserParamClick()">
                    Задать пользовательскую настройку
                </button>
            </div>

<!--            <sdi-code *ngIf="pluginUserSettings$ | async as pluginUserSettings" -->
<!--                      langCode="ts"-->
<!--            >{{pluginUserSettings | json}}</sdi-code>-->
            <pre class="mt-4">{{pluginUserSettings$ | async | json}}</pre>
        </section>
    `
})
export class CdPluginSupportServiceDemoComponent extends CdDemoComponent {

    constructor(
        private pluginSupportService: PluginSupportService,
        private notificationService: NotificationService,
        private globalModalsService: GlobalModalsService
    ) {
        super();
    }

    pluginSettings$ = this.pluginSupportService.getPluginSettings$(CD_PLUGIN_NAME);
    pluginUserSettings$ = this.pluginSupportService.getPluginUserSettings$(CD_PLUGIN_NAME);


    onGetPluginSettingsSyncClick() {
        const settings = this.pluginSupportService.getPluginSettings(CD_PLUGIN_NAME);
        this.notificationService.success(`<h4>Настройки расширения</h4>`
            + `<pre class="mt-32">${JSON.stringify(settings, null, 4)}</pre>`);
    }

    onSetUserParamClick() {
        let paramName: string;
        let paramValue: string;
        this.globalModalsService.openDialog('ParamsInputDialogComponent', {
            header: $localize`Пользовательская настройка`,
            cardRows: [
                new PrimitiveValueCardRow(null, new CardRowParams(null, 'paramName', 'Ключ', '', 'STRING',
                    v => paramName = v)),
                new PrimitiveValueCardRow(null, new CardRowParams(null, 'paramValue', 'Значение', '', 'STRING',
                    v => paramValue = v)),
            ],
            canApplyFn: () => !!paramName,
            onApplyClickFn: () => this.pluginSupportService.setPluginUserSettingsParam(CD_PLUGIN_NAME, paramName, paramValue)
        });
    }

}
