<?php
namespace JetStudio;

use Jet\Translator;
use Jet\UI;
use Jet\Locale;
use Jet\Tr;
use Jet\UI_dialog;

?>
<script type="text/javascript">
	const Dialog_SelectLocale = {
		open: function( callback ) {
			Dialog_SelectLocale.responseCallback = callback;

			Dialog_SelectLocale.resetSearch();

			$('#dialog_select_locale').modal('show');
		},

		responseCallback: function( locale_data ) {
			console.debug( 'Selected:', locale_data );
		},

		search: function() {
			let value = $('#search_locale_value').val();

			if(!value) {
				Dialog_SelectLocale.resetSearch();
				return;
			}

			value = value.toLowerCase();

			$('.locale-row').each( function (index, row) {
				row = $(row);

				const name = row.data('name').toLowerCase();
				const name_local = row.data('nameLocal').toLowerCase();
				const locale = row.data('locale').toLowerCase();

				if(
					name.includes( value ) ||
					name_local.includes( value ) ||
					locale.includes( value )
				) {
					row.show();
				} else {
					row.hide();
				}

			} );

		},

		resetSearch: function() {
			$('#search_locale_value').val('');

			$('.locale-row').show();
		},

		select: function( locale ) {
			const locale_row = $('#locale_' + locale);

			const locale_data = {
				locale: locale,
				name: locale_row.data('name'),
				name_local: locale_row.data('nameLocal')
			};

			Dialog_SelectLocale.responseCallback( locale_data );

			$('#dialog_select_locale').modal('hide');
		}

	};

</script>

<?php
$dialog = UI::dialog('dialog_select_locale', Tr::_('Select locale', [], Translator::COMMON_DICTIONARY), UI_dialog::SIZE_LARGE);

echo $dialog->start();
?>
	<?=JetStudio_UI::search(
		id: 'search_locale_value',
		placeholder: Tr::_('Search for locale ...', dictionary:  Translator::COMMON_DICTIONARY),
		search_action: 'Dialog_SelectLocale.search();',
		search_reset_action: 'Dialog_SelectLocale.resetSearch();') ?>


	<div style="height: 400px;overflow: auto;margin-top: 20px;">
		<table class="table table-striped">
		<?php
		$current_locale = Locale::getCurrentLocale();
		foreach( Locale::getAllLocalesList() as $l=>$name ):
			$l = new Locale($l);
			?>
			<tr
				class="locale-row"
				id="locale_<?=$l?>"
				data-name="<?=$l->getName($current_locale)?>"
				data-name-local="<?=$l->getName($l)?>"
				data-locale="<?=$l?>"
				style="cursor: pointer;"
				onclick="Dialog_SelectLocale.select('<?=$l?>');"
			>
				<td style="padding: 5px;font-size: 30px;"><?=UI::flag($l)?></td>

				<td><?=$l?></td>
				<td><?=$l->getName($current_locale)?></td>
				<td><?=$l->getName($l)?></td>

			</tr>
		<?php endforeach; ?>
		</table>
	</div>
	<?php
echo $dialog->end();

