/**
 *  ---------
 * |.##> <##.|  Open Smart Card Development Platform (www.openscdp.org)
 * |#       #|
 * |#       #|  Copyright (c) 1999-2006 CardContact Software & System Consulting
 * |'##> <##'|  Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
 *  ---------
 *
 *  This file is part of OpenSCDP.
 *
 *  OpenSCDP is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  OpenSCDP is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OpenSCDP; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @fileoverview Plug-In
 */

var File = require("scsh/file/File").File;
var FileEncryptor = require("scsh/file/FileEncryptor").FileEncryptor;



/**
 * Create a plug-in instance
 *
 * @constructor
 * @class Key Manager Plug-In for file encryption.
 * @param {KeyManager] km the associated key manager
 */
function EncryptionPlugin(km) {
	this.km = km;
}

// All plug-ins must export a symbol "Plugin"
exports.Plugin = EncryptionPlugin;

EncryptionPlugin.ENCRYPT_FILE = "Encrypt File";
EncryptionPlugin.DECRYPT_FILE = "Decrypt File";



/**
 * Add an entry to the context menu associated with a key in the outline
 *
 * @param {String[]} contextMenu the list of entries in the context menu
 * @param {Number} authenticationState the status returned in the last authentication query (SW1/SW2)
 * @param {Outline} keynode the node created for this key before it is added to the outline
 */
EncryptionPlugin.prototype.addKeyContextMenu = function(contextMenu, authenticationState, keynode) {
	if (authenticationState == 0x9000) {
		var type = keynode.key.getType();
		if (type == "AES") {
			contextMenu.push(EncryptionPlugin.ENCRYPT_FILE);
		}
		if ((type == "AES") || (type == "EC")) {
			contextMenu.push(EncryptionPlugin.DECRYPT_FILE);
		}
	}
}



/**
 * Handle action triggered from the outline context menu
 *
 * @param {Outline} source the source outline node of this action
 * @param {String} action the action selected from the context menu
 * @type Boolean
 * @return true if the action was handled
 */
EncryptionPlugin.prototype.actionListener = function(source, action) {
	switch(action) {
		case EncryptionPlugin.ENCRYPT_FILE:
			this.encryptFile(source);
			return true;
		case EncryptionPlugin.DECRYPT_FILE:
			this.decryptFile(source);
			return true;
	}
	return false;
}



/**
 * Prompt for a file and encrypt.
 */
EncryptionPlugin.prototype.encryptFile = function(source, action) {
	print("");
	print("WARNING: This is a proof-of-concept only and file formats may change at any time");
	print("         Use for testing an evaluation only.");

	var modes = [ "Use AES directly (Native)", "Use derived AES key (Derived)" ];

	var mode = Dialog.prompt("Select mode", modes[0], modes);
	if (!mode) {
		return;
	}

	var variant = mode == modes[0] ? FileEncryptor.NATIVE : FileEncryptor.DERIVED;

	var fname = "";
	if (this.lastPlainFileName) {
		fname = this.lastPlainFileName;
	}

	var fname = Dialog.prompt("Select file to encrypt", fname, null, "");
	if (!fname) {
		return;
	}

	this.lastPlainFileName = fname;

	var f = new File(fname);
	var bin = f.readAllAsBinary();
	f.close();

	if (variant == FileEncryptor.NATIVE) {
		var duration = Math.trunc(bin.length / 5000) + 1;
		print("Encryption of " + bin.length + " bytes in Native mode will take approximately " + duration + " seconds");
		if (duration > 60) {
			if (!Dialog.prompt("Continue ?")) {
				return;
			}
		}
	}

	fname = fname + ".enc";
	var fname = Dialog.prompt("Save encrypted file as", fname, null, "");
	if (!fname) {
		return;
	}

	var f = new File(fname);
	if (f.exists()) {
		if (Dialog.prompt("File does already exist. Overwrite ?") == null) {
			return;
		}
	}

	var fe = new FileEncryptor(this.km.sc, variant);

	fe.deriveKey(source.key);

	var bin = fe.encrypt(bin);

	f.writeAll(bin);
	f.close();
	print("Encryption complete.");
}



EncryptionPlugin.prototype.decryptFile = function(source, action) {
	var fname = "";
	if (this.lastPlainFileName) {
		fname = this.lastPlainFileName + ".enc";
	}

	var fname = Dialog.prompt("Select encrypted file", fname, null, "");
	if (!fname) {
		return;
	}

	var f = new File(fname);
	var bin = f.readAllAsBinary();
	f.close();

	this.lastPlainFileName = fname.substring(0, fname.lastIndexOf("."));

	var fe = new FileEncryptor(this.km.sc);

	var ofs = fe.parseHeader(bin);

	var fname = Dialog.prompt("Save encrypted file as", this.lastPlainFileName, null, "");
	if (!fname) {
		return;
	}

	var f = new File(fname);

	if (f.exists()) {
		if (Dialog.prompt("File does already exist. Overwrite ?") == null) {
			return;
		}
	}

	fe.deriveKey(source.key);

	var bin = fe.decrypt(bin.bytes(ofs));

	f.writeAll(bin);
	f.close();
	print("Decryption complete.");
}



EncryptionPlugin.prototype.toString = function() {
	return "Encryption-Plugin";
}
