/* jslint node: true, esnext: true */

'use strict';

const path = require('path'),
	process = require('process'),
	ssh2 = require('ssh2'),
	endpoint = require('kronos-endpoint'),
	service = require('kronos-service');

/**
 *
 */
class ServiceAdmin extends service.Service {
	static get name() {
		return 'admin';
	}

	get type() {
		return ServiceAdmin.name;
	}

	constructor(config, owner) {
		super(config, owner);

		this.addEndpoint(new endpoint.ReceiveEndpoint('software', this)).receive = request => Promise.resolve({
			versions: process.versions,
			platform: process.platform
		});
	}

	get autostart() {
		return true;
	}

	_start() {
		return super._start().then(() => {
			return service.ServiceConsumerMixin.defineServiceConsumerProperties(this, {
				'listener': {
					name: 'koa-admin',
					type: 'koa',
					docRoot: path.join(__dirname, '../docRoot')
				}
			}, this.owner, true).then(() => {
				if (this.config.ssh) {
					this.sshServer = require('./ssh')(this, this.config.ssh);
				}

				return this.owner.loadFlowFromFile(path.join(__dirname, '..', 'admin.flow'));
			});
		});
	}

	_stop() {
		if (this.sshServer) {
			return super._stop().then(new Promise((fullfill, reject) => {
				this.sshServer.close((err) => {
					if (err) {
						reject(err);
						return;
					}
					delete this.sshServer;
					fullfill();
				});
			}));
		}

		return super._stop();
	}
}

module.exports.registerWithManager = manager =>
	manager.registerServiceFactory(ServiceAdmin).then(admin =>
		manager.declareService({
			'type': admin.name,
			'name': admin.name
		}));

@@ -623,24 +623,333 @@
 n true;%0A%09%7D%0A%0A
+%09get configurationAttributes() %7B%0A%09%09return Object.assign(%7B%0A%09%09%09ssh: %7B%0A%09%09%09%09description: 'ssh admin interface',%0A%09%09%09%09attributes: %7B%0A%09%09%09%09%09port: %7B%0A%09%09%09%09%09%09description: 'listen port',%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09hostKeys: %7B%0A%09%09%09%09%09%09description: 'server ssh private host key(s)'%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D, super.configurationAttributes);%0A%09%7D%0A%0A
 %09_start() %7B%0A
@@ -940,32 +940,32 @@
 %09%7D%0A%0A%09_start() %7B%0A
-
 %09%09return super._
@@ -1072,17 +1072,16 @@
 %09%09%09%09
-'
 listener
 ': %7B
@@ -1076,17 +1076,16 @@
 listener
-'
 : %7B%0A%09%09%09%09
@@ -1840,14 +1840,12 @@
 %0A%09%09%09
-'
 type
-'
 : ad
@@ -1861,14 +1861,12 @@
 %0A%09%09%09
-'
 name
-'
 : ad

declare ssh config options