import ko from 'ko';

import { Scope } from 'Common/Enums';
import { getNotification, i18n } from 'Common/Translator';
import { arrayLength } from 'Common/Utils';

import Remote from 'Remote/Admin/Fetch';

import { decorateKoCommands, showScreenPopup } from 'Knoin/Knoin';
import { AbstractViewPopup } from 'Knoin/AbstractViews';
import { AskPopupView } from 'View/Popup/Ask';

class PluginPopupView extends AbstractViewPopup {
	constructor() {
		super('Plugin');

		this.addObservables({
			saveError: '',
			id: '',
			name: '',
			readme: ''
		});

		this.config = ko.observableArray();

		this.addComputables({
			hasReadme: () => !!this.readme(),
			hasConfiguration: () => 0 < this.config().length
		});

		this.bDisabeCloseOnEsc = true;
		this.keyScope.scope = Scope.All;

		this.tryToClosePopup = this.tryToClosePopup.debounce(200);

		decorateKoCommands(this, {
			saveCommand: self => self.hasConfiguration()
		});
	}

	saveCommand() {
		const oConfig = {
			Id: this.id(),
			Settings: {}
		};

		this.config.forEach(oItem => {
			let value = oItem.value();
			if (false === value || true === value) {
				value = value ? 1 : 0;
			}
			oConfig.Settings[oItem.Name] = value;
		});

		this.saveError('');
		Remote.request('AdminPluginSettingsUpdate',
			iError => iError
				? this.saveError(getNotification(iError))
				: this.cancelCommand(),
			oConfig);
	}

	onShow(oPlugin) {
		this.id('');
		this.name('');
		this.readme('');
		this.config([]);

		if (oPlugin) {
			this.id(oPlugin.Id);
			this.name(oPlugin.Name);
			this.readme(oPlugin.Readme);

			const config = oPlugin.Config;
			if (arrayLength(config)) {
				this.config(
					config.map(item => {
						item.value = ko.observable(item.value);
						return item;
					})
				);
			}
		}
	}

	tryToClosePopup() {
		if (AskPopupView.hidden()) {
			showScreenPopup(AskPopupView, [
				i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'),
				() => this.modalVisibility() && this.cancelCommand()
			]);
		}
	}

	onBuild() {
		shortcuts.add('escape', '', Scope.All, () => {
			if (this.modalVisibility()) {
				this.tryToClosePopup();
				return false;
			}
		});
	}
}

export { PluginPopupView, PluginPopupView as default };