<!--
 ~ Copyright 2022 youngmonkeys.org
 ~ 
 ~ Licensed under the ezyplatform, Version 1.0.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~ 
 ~     https://youngmonkeys.org/licenses/ezyplatform-1.0.0.txt
 ~ 
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="content">
	<div class="modal fade pt-4rem" id="apply-module-version-failed-modal">
		<div class="modal-dialog modal-md">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title" id="applyFailedTitle">[[#{apply_failed}]]</h4>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<div class="mt-2 pl-5 text-danger d-none" id="missingDependenciesDivApplyFailed">
						<span>[[#{missing_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_install_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="missingDependenciesOlApplyFailed">
						</ol>
					</div>
					<div class="mt-2 pl-5 text-danger d-none" id="needToUpdateDependenciesDivApplyFailed">
						<span>[[#{need_to_update_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_update_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="needToUpdateDependenciesOlApplyFailed">
						</ol>
					</div>
					<div class="mt-2 pl-5 text-danger d-none" id="inactiveDependenciesDivApplyFailed">
						<span>[[#{inactive_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_activate_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="inactiveDependenciesOlApplyFailed">
						</ol>
					</div>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<div class="modal fade pt-4rem" id="activate-module-modal">
		<div class="modal-dialog modal-md">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title" id="activateModuleTitle">[[#{activate_module}]]</h4>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<form id="activateModuleForm" class="pl-5" onsubmit="return false;">
					</form>
					<div class="mt-2 pl-5 text-danger d-none" id="missingDependenciesDiv">
						<span>[[#{missing_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_install_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="missingDependenciesOl">
						</ol>
					</div>
					<div class="mt-2 pl-5 text-danger d-none" id="needToUpdateDependenciesDiv">
						<span>[[#{need_to_update_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_update_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="needToUpdateDependenciesOl">
						</ol>
					</div>
					<div class="mt-2 pl-5 text-danger d-none" id="inactiveDependenciesDiv">
						<span>[[#{inactive_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_activate_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="inactiveDependenciesOl">
						</ol>
					</div>
					<div class="mt-2 pl-5 text-danger d-none" id="needToApplyDependenciesDiv">
						<span>[[#{plugins_need_to_apply_new_version}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_apply_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="needToApplyDependenciesOl">
						</ol>
						<div th:if="${osType.toString() == 'WINDOWS'}"
							 class="mt-3"
							 th:utext="#{windows_must_update_manually}"></div>
					</div>
				</div>
				<div class="modal-footer justify-content-between">
					<button type="button" class="btn btn-default" data-dismiss="modal">
						[[#{cancel}]]
					</button>
					<div>
						<small th:if="${osType.name() == 'WINDOWS'}">
							[[#{window_manually_restart}]]
						</small>
						<button type="button" class="btn btn-outline-primary" onclick="ezyadmin.onActivateModuleClick();">
							[[#{activate}]]
						</button>
						<button th:if="${osType.name() != 'WINDOWS'}" type="button" class="btn btn-primary"
								onclick="ezyadmin.onActivateModuleClick(true);">
							[[#{activate}]] & [[#{restart}]]
						</button>
					</div>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<div class="modal fade pt-4rem" id="deactivate-module-modal">
		<div class="modal-dialog modal-md">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title" id="deactivateModuleTitle">
						[[#{deactivate_module}]]
					</h4>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<form id="deactivateModuleForm" class="pl-5" onsubmit="return false;">
					</form>
					<div class="mt-2 pl-5 text-danger d-none" id="dependingPluginsDiv">
						<span>[[#{depending_plugins}]]
							<i class="fas fa-info-circle text-info"
							   data-toggle="tooltip" data-placement="top"
							   th:title="#{please_deactivate_them_to_continue}"></i>:
						</span>
						<ol class="m-0 pl-3" id="dependingPluginsOl">
						</ol>
					</div>
				</div>
				<div class="modal-footer justify-content-between">
					<button type="button" class="btn btn-default d-sm-block d-none" data-dismiss="modal">
						[[#{cancel}]]
					</button>
					<div>
						<small th:if="${osType.name() == 'WINDOWS'}">
							[[#{window_manually_restart}]]
						</small>
						<button type="button" class="btn btn-outline-info" onclick="ezyadmin.onDeactivateModuleClick();">
							[[#{deactivate}]]
						</button>
						<button th:if="${osType.name() != 'WINDOWS'}" type="button" class="btn btn-info"
								onclick="ezyadmin.onDeactivateModuleClick(true);">
							[[#{deactivate}]] & [[#{restart}]]
						</button>
					</div>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<div class="modal fade pt-4rem" id="delete-module-modal">
		<div class="modal-dialog modal-md">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title" id="deleteModuleTitle">
						[[#{delete_module}]]
					</h4>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<form id="deleteModuleForm" class="pl-5" onsubmit="return false;">
					</form>
				</div>
				<div class="modal-footer justify-content-between">
					<button type="button" class="btn btn-default" data-dismiss="modal">
						[[#{cancel}]]
					</button>
					<div>
						<button type="button" class="btn btn-outline-danger" onclick="ezyadmin.onDeleteModuleClick();">
							[[#{delete}]]
						</button>
						<button type="button" class="btn btn-danger" onclick="ezyadmin.onDeleteModuleClick(true);">
							[[#{delete}]] & [[#{restart}]]
						</button>
					</div>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal-dialog -->
</th:block>
<div th:fragment="upload-project" class="modal fade pt-4rem" id="upload-project">
	<div class="modal-dialog modal-md">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">
					[[#{upload_project}]]
				</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<form id="uploadProjectForm" method="post" enctype="multipart/form-data">
					<label id="uploadProjectFileErrorLabel" class="col-form-label text-danger pt-0 d-none" for="uploadProjectFile">
						<i class="far fa-times-circle"></i>
						<span class="line-break-anywhere" id="uploadProjectFileError">
							[[#{invalid}]]
						</span>
					</label>
					<div class="input-group">
						<div class="custom-file">
							<input name="file" type="file" id="uploadProjectFile"
								   class="custom-file-input"
								   accept=".zip">
							<label class="custom-file-label" for="uploadProjectFile" id="uploadProjectFileLabel">
								{project-name}-{version}.zip
							</label>
						</div>
					</div>
				</form>
			</div>
			<div class="modal-footer justify-content-between">
				<button type="button" class="btn btn-default" data-dismiss="modal">
					[[#{cancel}]]
				</button>
				<button type="button" class="btn btn-primary" onclick="ezyadmin.uploadProject();">
					[[#{upload}]]
				</button>
			</div>
		</div>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>
<div th:fragment="update-to-latest-ezyplatform" class="modal fade pt-4rem" id="update-to-latest-ezyplatform">
	<div class="modal-dialog modal-md">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">
					[[#{notification}]]
				</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				[[#{update_to_latest_ezyplatform_notification}]]
			</div>
			<div class="modal-footer justify-content-between">
				<button type="button" class="btn btn-default" data-dismiss="modal">
					[[#{close}]]
				</button>
				<a class="btn btn-primary" onclick="ezyadmin.uploadProject();" href="/ezyplatform">
					[[#{update}]]
				</a>
			</div>
		</div>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>
<script th:fragment="scripts">
// ============== activate module ===========
ezyadmin.showActivateModuleModal = function(
	moduleType,
	moduleName,
	moduleDisplayName,
	moduleVersion
) {
	$('#missingDependenciesDiv').addClass('d-none');
	$('#needToUpdateDependenciesDiv').addClass('d-none');
	$('#inactiveDependenciesDiv').addClass('d-none');
	$('#needToApplyDependenciesDiv').addClass('d-none');
	ezyadmin.showModuleModal(
		'activate',
		moduleType,
		moduleName,
		moduleDisplayName,
		moduleVersion
	);
}

ezyadmin.hideActivateModuleModal = function() {
	$('#delete-module-modal').modal('hide');
}

// ============== deactivate module ===========
ezyadmin.showDeactivateModuleModal = function(
	moduleType,
	moduleName,
	moduleDisplayName,
	moduleVersion
) {
	$('#dependingPluginsDiv').addClass('d-none');
	ezyadmin.showModuleModal(
		'deactivate',
		moduleType,
		moduleName,
		moduleDisplayName,
		moduleVersion
	);
}

ezyadmin.hideDeactivateModuleModal = function() {
	$('#delete-module-modal').modal('hide');
}

// ============== delete module ===========
ezyadmin.showDeleteModuleModal = function(
	moduleType,
	moduleName,
	moduleDisplayName,
	moduleVersion
) {
	ezyadmin.showModuleModal(
		'delete',
		moduleType,
		moduleName,
		moduleDisplayName,
		moduleVersion
	);
}

ezyadmin.hideDeleteModuleModal = function() {
	$('#delete-module-modal').modal('hide');
}

// ============= onclick ===========
ezyadmin.onActivateModuleClick = function(restart) {
	ezyadmin.doModuleAction('activate', restart);
}

ezyadmin.onDeactivateModuleClick = function(restart) {
	ezyadmin.doModuleAction('deactivate', restart);
}

ezyadmin.onDeleteModuleClick = function(restart) {
	ezyadmin.doModuleAction('delete', restart);
}

ezyadmin.onActiveDependentPluginClick = function(projectName) {
	$.ajax({
        url: '/api/v1/projects/' + projectName,
        type: 'GET',
        dataType: 'json',
    })
    .done(function(project) {
		ezyadmin.showActivateModuleModal(
			project.firstModuleTypeName,
			project.name,
			project.displayName,
			project.version
		);
    })
    .fail(function(data) {
        ezyadmin.processGetApiErrors(data);
    });
}

// ============== common ===========
ezyadmin.showModuleModal = function(
	action,
	moduleType,
	moduleName,
	moduleDisplayName,
	moduleVersion
) {
	if (action != 'activate') {
		ezyadmin.needActiveModuleName = null;
	}
	ezyadmin.currentSelectedModuleAction = action;
	ezyadmin.currentSelectedModuleName = moduleName;
	var actionName = ezyadmin.messages[action];
	$('#' + action + 'ModuleTitle').text(actionName + ' ' + moduleDisplayName + ' ' + moduleVersion);
	var active = action == 'deactivate';
	$.ajax({
        url: '/api/v1/projects/' + moduleName + '/module-types?active=' + active,
        type: 'GET',
        dataType: 'json',
    })
    .done(function(moduleTypes) {
		$('#' + action + 'ModuleForm').html(ezyadmin.buildModuleTypesSelectHtml(moduleTypes));
    	$('#' + action + '-module-modal').modal('show');
    })
    .fail(function(e) {
    	ezyadmin.processGetApiErrors(e);
    });
}

ezyadmin.doModuleAction = function(action, restart) {
	ezyadmin.showLoadingScreen();
    var formData = ezyadmin.formDataToObject(action + 'ModuleForm');
    var moduleTypes = formData.moduleTypes;
    if (!Array.isArray(moduleTypes)) {
    	formData.moduleTypes = [moduleTypes];
    }
    ezyadmin.currentSelectedModuleTypes = formData.moduleTypes;
    if (restart) {
    	formData.restart = true;
    }
    var postAction = () => {
    	if (action == 'delete') {
			window.location = '/' + (ezyadmin.currentModuleType || 'plugin') + 's'
				+ (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
		} else {
			if (ezyadmin.currentSelectedModuleName == ezyadmin.needActiveModuleName) {
				ezyadmin.needActiveModuleName = null;
				ezyadmin.needActiveModuleTypes = null;
			}
			ezyadmin.reloadAfterDoModuleAction()
		};
    }
    $.ajax({
        type: (action == 'delete' ? 'DELETE' : 'POST'),
        url: '/api/v1/projects/' + ezyadmin.currentSelectedModuleName + (action == 'delete' ? '' : '/' + action),
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            if (restart) {
        		ezyadmin.ensureAdminRunning(postAction);
        	}
        	else {
        		postAction();
        	}
        },
        error: function (e) {
            ezyadmin.processUpdateApiErrors({}, e);
            if (e.status == 403) {
            	ezyadmin.processModuleActionErrors(e);
            }
            ezyadmin.hideLoadingScreen();
        }
    });
}

ezyadmin.reloadAfterDoModuleAction = function() {
	var params = [];
    if (ezyadmin.needActiveModuleName) {
        params.push('needActiveModuleName=' + ezyadmin.needActiveModuleName);
    }
    if (ezyadmin.needActiveModuleTypes && ezyadmin.needActiveModuleTypes.length) {
		params.push('needActiveModuleTypes=' + ezyadmin.needActiveModuleTypes.join(','));
    }
    if (ezyadmin.lang) {
        params.push('lang=' + ezyadmin.lang);
    }
    var url = location.pathname;
    if (params.length) {
        url += '?' + params.join('&');
    }
    window.location = url;
}

ezyadmin.setNeedActiveModuleNameIfNotSet = function() {
	if (ezyadmin.currentSelectedModuleName
		&& !ezyadmin.needActiveModuleName
	) {
		ezyadmin.needActiveModuleName = ezyadmin.currentSelectedModuleName;
		ezyadmin.needActiveModuleTypes = ezyadmin.currentSelectedModuleTypes;
	}
	if (ezyadmin.currentSelectedModuleName == ezyadmin.needActiveModuleName) {
		ezyadmin.needActiveModuleTypes = ezyadmin.currentSelectedModuleTypes;
	}
}

ezyadmin.processModuleActionErrors = function(e, viewIdSuffix) {
	var errors = e.responseJSON;
	var suffix = viewIdSuffix || '';
	if (errors.projectMissingDependencies) {
		ezyadmin.setNeedActiveModuleNameIfNotSet();
		ezyadmin.buildMissingDependenciesHtml(
			errors.projectMissingDependencies,
			(html) => {
				$('#missingDependenciesOl' + suffix).html(html);
				$('#missingDependenciesDiv' + suffix).removeClass('d-none');
			}
		);
	} else if(errors.projectNeedToUpdateDependencies) {
		ezyadmin.setNeedActiveModuleNameIfNotSet();
		ezyadmin.buildNeedToUpdateDependenciesHtml(
			errors.projectNeedToUpdateDependencies,
			(html) => {
				$('#needToUpdateDependenciesOl' + suffix).html(html);
				$('#needToUpdateDependenciesDiv' + suffix).removeClass('d-none');
			}
		);
	} else if (errors.projectInactiveDependencies) {
		ezyadmin.setNeedActiveModuleNameIfNotSet();
		ezyadmin.currentSelectedModuleName;
		var html = ezyadmin.buildInactiveDependenciesHtml(
			errors.projectInactiveDependencies
		);
		$('#inactiveDependenciesOl' + suffix).html(html);
		$('#inactiveDependenciesDiv' + suffix).removeClass('d-none');
	} else if (errors.projectDependingPlugins) {
		ezyadmin.setNeedActiveModuleNameIfNotSet();
		var html = ezyadmin.buildDependingDependenciesHtml(
			errors.projectDependingPlugins
		);
		$('#dependingPluginsOl' + suffix).html(html);
		$('#dependingPluginsDiv' + suffix).removeClass('d-none');
	} else if (errors.projectNeedToApplyDependencies) {
		ezyadmin.setNeedActiveModuleNameIfNotSet();
		var html = ezyadmin.buildNeedToApplyDependenciesHtml(
			errors.projectNeedToApplyDependencies
		);
		$('#needToApplyDependenciesOl' + suffix).html(html);
		$('#needToApplyDependenciesDiv' + suffix).removeClass('d-none');
	}
}

ezyadmin.buildMissingDependenciesHtml = function(dependencies, callback) {
	var projectAndVersions = [];
	dependencies.forEach(it => {
		projectAndVersions.push(it.projectName + ':' + it.projectVersion);
	});
	ezyadmin.findMarketUrlOfProjects(
		0,
		projectAndVersions,
		{},
		function (marketUrlByProjectName) {
			callback(
				ezyadmin.doBuildMissingDependenciesHtml(
					dependencies,
					marketUrlByProjectName
				)
			);
		}
	);
}

ezyadmin.findMarketUrlOfProjects = function(
	marketIndex,
	projectAndVersions,
	marketUrlByProjectName,
	callback
) {
	var marketUrl = ezyadmin.marketUrls[marketIndex];
	var isLastMarket = marketIndex >= ezyadmin.marketUrls.length - 1;
	$.ajax({
        type: 'GET',
        url: '/api/v1/released-projects-existing-filter?marketUrl='
        	+ encodeURIComponent(marketUrl)
        	+ '&projectAndVersions='
        	+ encodeURIComponent(projectAndVersions.join(',')),
        contentType: 'application/json',
        success: function (existingProjects) {
            existingProjects.forEach(projectName => {
            	marketUrlByProjectName[projectName] = marketUrl;
            });
            var remainProjectAndVersions = projectAndVersions.filter(
            	it => !marketUrlByProjectName[it.split(':')[0]]
            );
            if (remainProjectAndVersions.length && !isLastMarket) {
            	ezyadmin.findMarketUrlOfProjects(
            		marketIndex + 1,
            		remainProjectAndVersions,
            		marketUrlByProjectName,
            		callback
            	);
            	return;
            }
			callback(marketUrlByProjectName);
        },
        error: function (data) {
        	if (!isLastMarket) {
        		ezyadmin.findMarketUrlOfProjects(
        			marketIndex + 1,
        			projectAndVersions,
        			marketUrlByProjectName,
        			callback
        		);
        		return;
        	}
            ezyadmin.processGetApiErrors(data);
            callback(marketUrlByProjectName);
        }
    });
}

ezyadmin.doBuildMissingDependenciesHtml = function(
	dependencies,
	marketUrlByProjectName
) {
	var html = '';
	dependencies.forEach(it => {
		html += `
			<li>
				${it.projectName}: ${it.projectVersion}
				${marketUrlByProjectName[it.projectName] ? `
					<span class="text-secondary ml-1 mr-1">|</span>
					<span class="text-primary cursor-pointer" onclick="ezyadmin.installProject('${it.projectName}', '${it.projectVersion}', '${marketUrlByProjectName[it.projectName]}')">
						${ezyadmin.messages.install.toLowerCase()} <i class="fas fa-download"></i>
					</span>
				` : ''}
				<span class="text-secondary ml-1 mr-1">|</span>
				<span class="text-primary cursor-pointer" onclick="ezyadmin.showUploadProjectModal()">
					${ezyadmin.messages.upload.toLowerCase()} <i class="fas fa-upload"></i>
				</span>
			</li>
		`;
	});
	return html;
}

ezyadmin.buildNeedToUpdateDependenciesHtml = function(dependencies, callback) {
	var projectAndVersions = [];
	dependencies.forEach(it => {
		projectAndVersions.push(it.projectName + ':' + it.projectVersion);
	});
	ezyadmin.findMarketUrlOfProjects(
		0,
		projectAndVersions,
		{},
		function (marketUrlByProjectName) {
			var html = '';
			dependencies.forEach(it => {
				html += `
					<li>
						${it.projectName}: ${it.projectVersion}
						${marketUrlByProjectName[it.projectName] ? `
							<span class="text-secondary ml-1 mr-1">|</span>
							<span class="text-primary cursor-pointer" onclick="ezyadmin.installProject('${it.projectName}', '${it.projectVersion}', '${marketUrlByProjectName[it.projectName]}')">
								${ezyadmin.messages.install.toLowerCase()} <i class="fas fa-download"></i>
							</span>
						` : ''}
						<span class="text-secondary ml-1 mr-1">|</span>
						<span class="text-primary cursor-pointer" onclick="ezyadmin.showUploadProjectModal()">
							${ezyadmin.messages.upload.toLowerCase()} <i class="fas fa-upload"></i>
						</span>
					</li>
				`;
			});
			callback(html);
		}
	);
}

ezyadmin.buildInactiveDependenciesHtml = function(dependencies) {
	var html = '';
	dependencies.forEach(it => {
		html += `
			<li>
				${it}
				<span class="text-secondary ml-1 mr-1">|</span>
				<span class="text-primary cursor-pointer" onclick="ezyadmin.onActiveDependentPluginClick('${it}')">
					${ezyadmin.messages.activate.toLowerCase()} <i class="fas fa-paper-plane"></i>
				</span>
			</li>
		`;
	});
	return html;
}

ezyadmin.buildDependingDependenciesHtml = function(dependencies) {
	var html = '';
	dependencies.forEach(it => {
		html += `<li>${it}</li>`;
	});
	return html;
}

ezyadmin.buildNeedToApplyDependenciesHtml = function(dependencies) {
	var html = '';
	dependencies.forEach(it => {
		html += `
			<li>
				${it.projectName}: ${it.projectVersion}
				<span class="text-secondary ml-1 mr-1">|</span>
				<span class="text-primary cursor-pointer" onclick="ezyadmin.onRestartToApplyButtonClick('${it.projectName}', '${it.projectName}', '${it.projectVersion}')">
					${ezyadmin.messages.apply.toLowerCase()} <i class="fas fa-location-arrow"></i>
				</span>
			</li>
		`;
	});
	return html;
}

ezyadmin.buildModuleTypesSelectHtml = function(moduleTypes) {
	var checkedModuleTypes = moduleTypes;
	if (ezyadmin.currentSelectedModuleAction == 'activate'
		&& ezyadmin.currentSelectedModuleName == ezyadmin.needActiveModuleName
		&& ezyadmin.needActiveModuleTypes
		&& ezyadmin.needActiveModuleTypes.length
	) {
		checkedModuleTypes = ezyadmin.needActiveModuleTypes;
	}
	var html = '';
	moduleTypes.forEach(moduleType => {
		html += `
			<div class="form-check">
				<input name="moduleTypes"
					   class="form-check-input wh-1rem"
					   type="checkbox"
					   value="${moduleType}"
					   ${checkedModuleTypes.indexOf(moduleType) >= 0 ? 'checked' : ''}>
				<label class="form-check-label">
					${moduleType}
				</label>
			</div>`;
	});
	return html;
}

$(document).ready(() => {
	ezyadmin.needActiveModuleName = ezyadmin.getCurrentUrlParameter(
		'needActiveModuleName'
	);
	if (ezyadmin.needActiveModuleName) {
		ezyadmin.onActiveDependentPluginClick(ezyadmin.needActiveModuleName);
	}
	ezyadmin.needActiveModuleTypes = ezyadmin.getCurrentUrlParameter(
		'needActiveModuleTypes'
	);
	if (ezyadmin.needActiveModuleTypes) {
		ezyadmin.needActiveModuleTypes = ezyadmin.needActiveModuleTypes.split(',');
	}
});
</script>
<script th:fragment="upload-project-scripts">
// ========== upload module ==========
ezyadmin.uploadProjectView = {
    name: 'uploadProject',
    chooseFileLabelText: $('#uploadProjectFileLabel').text()
};
bsCustomFileInput.init();

ezyadmin.showUploadProjectModal = function() {
	if (ezyadmin.hasNewPlatformVersion) {
		ezyadmin.showUpdateToLatestEzyPlatformModal();
		return;
	}
    $('#uploadProjectFileErrorLabel').addClass('d-none');
	$('#upload-project').modal('show');
}

ezyadmin.onUpdateManuallyButtonClick = function() {
    ezyadmin.showUploadProjectModal();
}

ezyadmin.uploadProject = function() {
    ezyadmin.showLoadingScreen({showPercent: true});
    var formData = new FormData();
    var data = new FormData(document.querySelector('#uploadProjectForm'));
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/api/v1/projects/upload",
        data: data,
        processData: false,
        contentType: false,
        cache: false,
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(event) {
				if (event.lengthComputable) {
                    var percentComplete = Math.round((event.loaded / event.total) * 100);
                    ezyadmin.setLoadingScreenPercent(percentComplete);
                }
            });
            return xhr;
        },
        success: function (module) {
        	if (ezyadmin.needActiveModuleName) {
				ezyadmin.reloadAfterDoModuleAction();
			} else {
				window.location = '/modules/' + module.projectName
					+ (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
			}
        },
        error: function(data, e) {
           ezyadmin.processUploadFileApiErrors(data, ezyadmin.uploadProjectView);
           ezyadmin.hideLoadingScreen();
        }
    });
}
</script>
<script th:fragment="update-to-latest-ezyplatform">
ezyadmin.showUpdateToLatestEzyPlatformModal = function() {
	$('#update-to-latest-ezyplatform').modal('show');
}
</script>
</body>
</html>
