import { Undecked } from '../../../../Core';
import { Deck } from '../../../../Decks/Deck';
import { ActionAPI } from '../../../ActionAPI';
import { EditorAPI, EditorAPI_Field } from '../../../EditorAPI';

declare var Undecked: Undecked;

module.exports = (actionAPI: ActionAPI) => {
	actionAPI.handle(
		(
			properties: Deck_ChangePage,
			status: (text: string, type?: 'info' | 'error' | 'warn') => void,
			executed: Deck
		) => {
			if (properties.page != undefined) {
				if (Undecked.Pages.exists(properties.page)) {
					var page = Undecked.Pages.get(properties.page);

					if (properties.decks != undefined && properties.decks.length > 0) {
						var changed = [];
						var failed = [];
						for (let i = 0; i < properties.decks.length; i++) {
							var serialNumber = properties.decks[i];

							if (Undecked.Decks.hasDeck(serialNumber) || serialNumber == 'current') {
								var deck = serialNumber != 'current' ? Undecked.Decks.getDeck(serialNumber) : executed;
								deck.setPageID(page.getID());
								changed.push(serialNumber);
							} else failed.push(serialNumber);
						}
						if (failed.length == 0)
							status(`Changed ${changed.length} deck(s) to page '${page.name}'`, 'info');
						else
							status(
								`Deck(s) '${failed.join(
									', '
								)}' were not found, only changed ${changed.length} deck(s) to page '${page.name}'`,
								'warn'
							);
					} else status('No decks selected', 'error');
				} else status('Page does not exist. Maybe it was removed?', 'error');
			} else status('Missing page property', 'error');
		}
	);

	actionAPI.onOpenEditor((editorAPI: EditorAPI, properties: Deck_ChangePage) => {
		editorAPI.onFieldChanges((fields: EditorAPI_Field[]) => {
			var fieldsObject = editorAPI.tools.objectifyFieldsValues(fields);
			editorAPI.saveProperties({
				decks: fieldsObject.deck,
				page: fieldsObject.page
			});
		});

		editorAPI.setFields([
			{
				id: 'deck',
				name: 'Deck',
				type: 'select',
				multi: true,
				value:
					properties.decks != undefined
						? properties.decks
						: [
								'current'
							],
				values: getDecksValues()
			},

			{
				id: 'page',
				name: 'Page',
				type: 'select',
				value: properties.page != undefined ? properties.page : '',
				values: getPageValues()
			}
		]);
	});

	function getDecksValues(): { id: string; text: string }[] {
		return [
			{ id: 'current', text: 'Current Deck' },
			...Undecked.Decks.getList().map((deck) => {
				return { id: deck.serialNumber, text: deck.name };
			})
		];
	}

	function getPageValues(): { id: string; text: string }[] {
		return Undecked.Pages.getNames().map((page) => {
			return { id: page.pageID, text: page.name };
		});
	}
};

interface Deck_ChangePage {
	decks: string[];
	page: string;
}
