[{isys_group name="tom.popup.qcw"}]
	<div id="popup-qcw">
        <div class="popup-header-ng">
            <h1>[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP"}]</h1>
            <button type="button" class="btn btn-secondary popup-closer ml-auto" title="[{isys type="lang" ident="LC__POPUP__CLOSE"}]" data-tooltip="1">
                <img alt="close" src="[{$dir_images}]axialis/user-interface/window-control-close.svg" />
            </button>
        </div>

		<div class="popup-content">
			<div class="container fl" style="width:49%;">
                <div class="p10">
                    <h3 class="mb20">[{isys type="lang" ident="LC__MODULE__QCW__SAVE_CURRENT_PROFILE"}]</h3>

                    <p>[{isys type="lang" ident="LC__MODULE__QCW__EXPORT_DESCRIPTION"}]</p>
					[{isys type="f_text" name="C__MODULE__QCW__CONFIG_TITLE"}]
					<button id="C__MODULE__QCW__SAVE_CONFIG" class="btn">
						<img src="[{$dir_images}]axialis/basic/symbol-ok.svg" />
						<span>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_SAVE"}]</span>
					</button>
				</div>
			</div>

			<div class="container fr" style="width:49%;">
                <div class="p10">
                    <h3 class="mb20">[{isys type="lang" ident="LC__MODULE__QCW__RESET"}]</h3>

                    <p>[{isys type="lang" ident="LC__MODULE__QCW__RESET_DESCRIPTION"}]</p>
					<button class="btn mt10" id="C__MODULE__QCW__RESET_CONFIG">
						<img src="[{$dir_images}]axialis/basic/button-remove.svg" />
						<span>[{isys type="lang" ident="LC__MODULE__QCW__BUTTON_RESET"}]</span>
					</button>
				</div>
			</div>

			<br class="cb" />
			<hr class="mt10 mb10" />

			<div class="container">
                <div class="p10">
                    <h3 class="mb20">[{isys type="lang" ident="LC__MODULE__QCW__ADD_PROFILES"}]</h3>

                    <p>[{isys type="lang" ident="LC__MODULE__QCW__IMPORT_DESCRIPTION"}]</p>

                    <div class="py5" style="height: 40px;">
                        [{isys type="f_file_ajax" name="qcw-profile-upload" uploadType="qcw.profile-upload"}]
                    </div>

					<table id="profile-table" class="mainTable mt15 border">
						<thead>
						<tr>
							<th>[{isys type="lang" ident="LC__MODULE__QCW__FILE"}]</th>
							<th>[{isys type="lang" ident="LC__MODULE__QCW__ACTIONS"}]</th>
						</tr>
						</thead>
						<tbody>
							<!-- Will be handled by JS -->
						</tbody>
					</table>

					<button id="C__MODULE__QCW__LOAD_CONFIG" class="btn mt15">
						<img src="[{$dir_images}]axialis/basic/symbol-angle-right.svg" alt="" />
						<span>[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__LOAD_PROFILE"}]</span>
					</button>
				</div>
			</div>
		</div>

		<div class="popup-footer-ng">
			<button type="button" class="btn popup-closer">
				<span>[{isys type="lang" ident="LC__VISUALIZATION_PROFILES__CLOSE_POPUP"}]</span>
			</button>
		</div>
	</div>
	<script type="text/javascript">
		(function () {
			'use strict';

            const $uploadContainer = $('qcw-profile-upload');

			var $popup       = $('popup-qcw'),
			    $saveButton  = $('C__MODULE__QCW__SAVE_CONFIG'),
			    $resetButton = $('C__MODULE__QCW__RESET_CONFIG'),
			    $loadButton  = $('C__MODULE__QCW__LOAD_CONFIG'),
				$profileTable = $('profile-table').down('tbody'),
				profiles = JSON.parse('[{$profiles|escape:"javascript"}]');

			$popup.on('click', '.popup-closer', function () {
				popup_close();
			});

			// Only submit the form, by click on this buttons.
			$saveButton.on('click', function () {
				var $profileTitleField = $('C__MODULE__QCW__CONFIG_TITLE'),
				    profileTitle = $profileTitleField.getValue();

				if (profileTitle.blank()) {
					$profileTitleField.highlight({startcolor:'#ffdddd', endcolor:'#ffffff', restorecolor:'#ffffff'});
					return;
				}

				$saveButton.disable()
                   .down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')
		           .next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]');

				new Ajax.Request('[{$ajax_url}]', {
					parameters: {
						action:       'saveProfile',
						profileTitle: profileTitle
					},
					method:     'post',
					onSuccess:  function (xhr) {
						var json = xhr.responseJSON;

						if (json.success) {
							$profileTitleField.setValue('');
							idoit.Notify.success('[{isys type="lang" ident="LC__INFOBOX__DATA_WAS_SAVED"}]');

							profiles.push(json.data);

							renderTable();

							$profileTable.down('tr[data-filename="' + json.data + '"]').highlight();
						} else {
							idoit.Notify.error(json.message, {sticky:true});
						}
					},
					onComplete: function () {
						$saveButton.enable()
							.down('img').removeClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/basic/symbol-ok.svg')
							.next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_SAVE"}]');
					}
				});
			});

			// Trigger an ajax call for the "reset" button.
			$resetButton.on('click', function () {
				if (confirm('[{isys type="lang" ident="LC__MODULE__QCW__RESET_CONFIRM" p_bHtmlEncode=0}]'))
				{
					$resetButton.disable()
                        .down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')
			            .next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]');

					new Ajax.Request('?ajax=1&call=quick_configuration_wizard', {
						parameters: {
							func: 'reset'
						},
						method:     'post',
						onSuccess:  function (xhr) {
							var json = xhr.responseJSON;
							$('loading-object-type').hide();

							if (json.success)
							{
								// If everything went fine, reload the page.
								idoit.Notify.success('[{isys type="lang" ident="LC__MODULE__QCW__RESET_SUCCESS"}]', {sticky: true});

								// This triggers a get request.
								window.location.reload(true);
							}
							else
							{
								// Do some error messaging.
								idoit.Notify.success(json.message, {sticky: true});
							}
						},
						onFailure:  function (xhr) {
							idoit.Notify.success(xhr.responseText, {sticky: true});
						},
						onComplete: function () {
							$resetButton
									.down('img').removeClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/basic/button-remove.svg')
									.next('span').update('[{isys type="lang" ident="LC__MODULE__QCW__BUTTON_RESET"}]');
						}
					});
				}
			});

			$popup.on('click', 'button[data-action="delete-profile"]', function (ev) {
				var $button  = ev.findElement('button'),
				    $tr      = $button.up('tr'),
					filename = $tr.readAttribute('data-filename');

				if (confirm('[{isys type="lang" ident="LC__MODULE__QCW__DELETE_FILE" p_bHtmlEncode=false}]'))
				{
					$button.disable().down('img')
                        .addClassName('animation-rotate')
                        .writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')

					new Ajax.Request('[{$ajax_url}]', {
						parameters: {
							action: 'deleteProfile',
							file:   filename
						},
						method:     'post',
						onSuccess:  function () {
							profiles = profiles.filter(function (profile) {
								return profile !== filename;
							});

							renderTable();
						},
						onComplete: function () {
							// In case of "failure" reset the button.
							$button.enable().down('img')
                                .removeClassName('animation-rotate')
                                .writeAttribute('src', window.dir_images + 'axialis/basic/symbol-cancel.svg');
						}
					});
				}
			});

			// Import profile to the database
            $loadButton.on('click', function () {
                const selectedProfiles = $profileTable.select(':checked').invoke('readAttribute', 'value');

                if (selectedProfiles.length > 0) {
                    $loadButton
                        .down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg')
                        .next('span').update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]');

                    new Ajax.Request('?ajax=1&call=quick_configuration_wizard', {
                        parameters: {
                            func:          'load_profiles',
                            profile_files: Object.toJSON(selectedProfiles)
                        },
                        method:     'post',
                        onSuccess:  function () {
                            window.location.reload(true);
                        },
                        onComplete: function () {
                            $loadButton
                                .down('img').removeClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/basic/symbol-angle-right.svg')
                                .next('span').update('[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__LOAD_PROFILE"}]');
                        }
                    });
                }
            });

            $uploadContainer.on('uploader:onComplete', function (ev) {
                const result = ev.memo.json.data.callbackResult;

                if (result.success) {
                    profiles.push(result.data);

                    renderTable();

                    $profileTable.down('[data-filename="' + result.data + '"]').highlight();
                } else {
                    idoit.Notify.error(result.message || '[{isys type="lang" ident="LC__MODULE__QCW__PROFILE_POPUP__UPLOAD_ERROR"}]', { sticky:true });
                }
            });

			function renderTable () {
				var $tr, i;

				$profileTable.update();

				if (!Object.isArray(profiles) || profiles.length === 0)
				{
					return;
				}

				profiles = profiles.uniq();

                for (i in profiles) {
                    if (!profiles.hasOwnProperty(i)) {
                        continue;
                    }

                    $tr = new Element('tr', { className: (i % 2 ? 'line0' : 'line1'), 'data-filename': profiles[i] })
                        .update(new Element('td')
                            .update(new Element('label')
                                .update(new Element('input', { type:'checkbox', className:'qcw_profile_files', value:profiles[i] }))
                                .insert(' ')
                                .insert(profiles[i])))
                        .insert(new Element('td', { className: 'p5' })
                            .update(new Element('a', { className:'btn btn-small mr5', href:idoit.Router.getRoute('system.file-download', { type: 'qcw.profile-download', identifier: profiles[i] }), type:'application/octet-stream', title:'[{isys type="lang" ident="LC__UNIVERSAL__DOWNLOAD_FILE" p_bHtmlEncode=false}]', 'data-tooltip': 1 })
                                .update(new Element('img', { src:window.dir_images + 'axialis/basic/symbol-download.svg' })))
                            .insert(new Element('button', { className:'btn btn-small', type:'button', 'data-action':'delete-profile', title:'[{isys type="lang" ident="LC__UNIVERSAL__DELETE_FILE" p_bHtmlEncode=false}]', 'data-tooltip': 1 })
                                .update(new Element('img', { src:window.dir_images + 'axialis/basic/symbol-cancel.svg' }))));

                    $profileTable.insert($tr);
                }
			}

			// Render the table.
			renderTable();
		})();
	</script>
[{/isys_group}]
