<!--
 ~ 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">
					</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>
				<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">
					</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">
					</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');
	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
) {
	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];
    }
    if (restart) {
    	formData.restart = true;
    }
    var postAction = () => {
    	if (action == 'delete') {
			window.location = '/' + (ezyadmin.currentModuleType || 'plugin') + 's'
				+ (ezyadmin.lang ? '?lang=' + ezyadmin.lang : '');
		} else {
			location.reload()
		};
    }
    $.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.processModuleActionErrors = function(e, viewIdSuffix) {
	var errors = e.responseJSON;
	var suffix = viewIdSuffix || '';
	if (errors.projectMissingDependencies) {
		ezyadmin.buildMissingDependenciesHtml(
			errors.projectMissingDependencies,
			(html) => {
				$('#missingDependenciesOl' + suffix).html(html);
				$('#missingDependenciesDiv' + suffix).removeClass('d-none');
			}
		);
	} else if(errors.projectNeedToUpdateDependencies) {
		var html = ezyadmin.buildNeedToUpdateDependenciesHtml(
			errors.projectNeedToUpdateDependencies
		);
		$('#needToUpdateDependenciesOl' + suffix).html(html);
		$('#needToUpdateDependenciesDiv' + suffix).removeClass('d-none');
	} else if (errors.projectInactiveDependencies) {
		var html = ezyadmin.buildInactiveDependenciesHtml(
			errors.projectInactiveDependencies
		);
		$('#inactiveDependenciesOl' + suffix).html(html);
		$('#inactiveDependenciesDiv' + suffix).removeClass('d-none');
	} else if (errors.projectDependingPlugins) {
		var html = ezyadmin.buildDependingDependenciesHtml(
			errors.projectDependingPlugins
		);
		$('#dependingPluginsOl' + suffix).html(html);
		$('#dependingPluginsDiv' + suffix).removeClass('d-none');
	}
}

ezyadmin.buildMissingDependenciesHtml = function(dependencies, callback) {
	var projectAndVersions = [];
	dependencies.forEach(it => {
		projectAndVersions.push(it.projectName + ':' + it.projectVersion);
	});
	var url = '/api/v1/released-projects-existing-filter' +
		'?projectAndVersions=' + projectAndVersions.join(',');
	$.ajax({
        type: 'GET',
        url: url,
        contentType: 'application/json',
        success: function (existingProjects) {
            var existingProjectMap = {};
            existingProjects.forEach(projectName => {
            	existingProjectMap[projectName] = true;
            });
			var html = ezyadmin.doBuildMissingDependenciesHtml(
				dependencies,
				existingProjectMap
			);
			callback(html);
        },
        error: function (data) {
            ezyadmin.processGetApiErrors(data);
            ezyadmin.doBuildMissingDependenciesHtml(
				dependencies,
				{}
			);
        }
    });
}

ezyadmin.doBuildMissingDependenciesHtml = function(
	dependencies,
	existingProjectMap
) {
	var html = '';
	dependencies.forEach(it => {
		html += `
			<li>
				${it.projectName}: ${it.projectVersion}
				${existingProjectMap[it.projectName] ? `
					<span class="text-secondary ml-1 mr-1">|</span>
					<span class="text-primary cursor-pointer" onclick="ezyadmin.installProject('${it.projectName}', '${it.projectVersion}')">
						${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) {
	var projectAndVersions = [];
	dependencies.forEach(it => {
		projectAndVersions.push(it.projectName + ':' + it.projectVersion);
	});
	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.installProject('${it.projectName}', '${it.projectVersion}')">
					${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.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.buildModuleTypesSelectHtml = function(moduleTypes) {
	var html = '';
	moduleTypes.forEach(moduleType => {
		html += `
			<div class="form-check">
				<input name="moduleTypes" class="form-check-input" type="checkbox" value="${moduleType}" checked>
				<label class="form-check-label">
					${moduleType}
				</label>
			</div>`;
	});
	return html;
}
</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,
        timeout: 600000,
        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) {
            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>
