var Cert = {
	params: {},

	checkParams: function (params) {
		if (typeof params !== 'object') {
			throw 'Error of parameter processing.'
		}

		['hostnames'].forEach(function (field) {
			if (typeof params[field] === 'undefined' || params[field] === '') {
				throw 'Required params is not set:' + field + '.';
			}
		});

		['port', 'ip', 'check'].forEach(function (field) {
			if (typeof params[field] === 'undefined') {
				params[field] = '';
			}
		});

		Cert.params = params;
	},

	parseParams: function () {
		var array_hostname = Cert.params['hostnames'].split(','),
			array_port = Cert.params['port'].split(','),
			array_ip = Cert.params['ip'].split(','),
			data = [],
			errors = [];

		for (var i = 0; i < Math.max(array_hostname.length, array_port.length, array_ip.length); i++) {
			if (typeof array_hostname[i] === 'undefined' || array_hostname[i].trim() === '') {
				if (Cert.params['check'] === 'STRICT') {
					throw 'Invalid parameter "{' + '$CERT.WEBSITE.HOSTNAME} [' + i + ']" : host is required.'
				} else {
					errors.push(i);
					continue;
				}
			}

			item_name = array_hostname[i].trim();
			ip = typeof array_ip[i] === 'undefined' ? '' : array_ip[i].trim();
			port = typeof array_port[i] === 'undefined' ? '' : array_port[i].trim();

			is_empty_ip = ip === '';
			is_empty_port = port === '' || port === '443';

			if (!is_empty_port) {

				if (!/^\d+$/.test(port)) {
					throw 'Invalid parameter "{' + '$CERT.WEBSITE.PORT} [' + i + ']" : error parse value "' + port + '".';
				}

				port_number = parseInt(port);

				if (port_number < 1 || port_number > 65535) {
					throw 'Invalid parameter "{' + '$CERT.WEBSITE.PORT} [' + i + ']" : "' + port_number + '" is out of range 1-65535.';
				}
			}

			if (!is_empty_ip && is_empty_port) {
				item_name += ', ' + ip;
			} else if (is_empty_ip && !is_empty_port) {
				item_name += ':' + port;
			} else if (!is_empty_ip && !is_empty_port) {
				item_name += ', ' + ip + ':' + port;
			}

			data.push(
				{
					hostname: array_hostname[i].trim(),
					port: port,
					ip: ip,
					key: item_name
				}
			);
		}

		return {
			data: data,
			errors: errors
		};
	}
};

var lld_data = {
	error: {
		message: '',
		code: 0
	},
	data: []
};

try {
	Cert.checkParams(JSON.parse(value));
	var parse_result = Cert.parseParams();
	if (parse_result['errors'].length > 0) {
		lld_data.error.message = 'Incorrect parameters: [' + parse_result['errors'].toString() + '].';
		lld_data.error.code = 1;
	}
	lld_data.data = parse_result['data']
}
catch (error) {
	error += (String(error).endsWith('.')) ? '' : '.';
	lld_data.error.message = error;
	lld_data.error.code = 2;
}

return JSON.stringify(lld_data);