/*
 * Licence Library - bootstrap configuration for all Tigase projects
 * Copyright (C) 2011 Tigase, Inc. (office@tigase.com) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */
/*
 Retrieve code for manual licence retrieval
 AS:Description: Force retrieving licence from the server
 AS:CommandId: retrieve-licence-from-server
 AS:Component: vhost-man
 AS:Group: Licence
 */
package tigase.admin

import tigase.licence.LicenceChecker
import tigase.server.Command
import tigase.server.Iq

import java.text.SimpleDateFormat

def p = (Iq) packet

def admins = (Set) adminsSet
def stanzaFromBare = p.getStanzaFrom().getBareJID()
def isServiceAdmin = admins.contains(stanzaFromBare)

if (!isServiceAdmin) {
	def result = p.commandResult(Command.DataType.result);
	Command.addTextField(result, "Error", "You are not service administrator");
	return result
}

String componentId = Command.getFieldValue(p, "component-id");
if (componentId == null) {
	def possibleValues = (tigase.licence.LicenceChecker.getLicencedComponents() as List).sort();

	def result = p.commandResult(Command.DataType.form);

	Command.addTitle(result,
					 "Please select component ID for which you want to retrieve code required for manual licence retrieval")
	Command.addFieldValue(result, "component-id", "", "Component ID", possibleValues as String[],
						  possibleValues as String[], "list-single")
	return result
}

def result = p.commandResult(Command.DataType.result)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

def checker = LicenceChecker.getLicenceChecker(componentId);
def validUntilOld = checker.getValidUntil();
def digestOld = checker.getLicenceDigest();

try {
	checker.reloadLicenceFromServer();

	def validUntilNew = checker.getValidUntil();
	def digestNew = checker.getLicenceDigest();

	Command.addTitle(result, "Licence code reload has been completed");

	Command.addFieldValue(result, "Previous licence valid-until", sdf.format(validUntilOld), "text-single");
	Command.addFieldValue(result, "Previous licence digest", digestOld, "text-single");
	Command.addFieldValue(result, "Loaded licence valid-until", sdf.format(validUntilNew), "text-single");
	Command.addFieldValue(result, "Loaded licence digest", digestNew, "text-single");

} catch (Exception e) {
	Command.addTitle(result, "Reloading of the licence failed!");
}


return result;