import { Types } from '../types';
import { LocalizedStrings } from '../../services/localizedStringsService';
import * as VariableValueMenu from './variable_value_menu';
import * as CommandsManagement from '../commands';
import * as GenericExpressionManagement from './generic_expression';
import * as Models from '../ivprog_elements';
import * as CodeGenerator from '../code_generator';

export function createFloatingCommand () {
	return $('<div class="ui return created_element"> <i class="ui icon small reply"></i> <span> '+LocalizedStrings.getUI('text_return')+' </span></div>');
}

export function renderCommand (command, function_obj) {
	var el = $('<div class="ui return command_container"> <i class="ui icon small reply command_drag"></i> <i class="ui icon times red button_remove_command"></i> <span class="span_command_spec"> '+LocalizedStrings.getUI('text_return')+' </span>  <div class="expression_elements"></div><span class="textual_expression" style="display: none; margin-left: 1rem;"></span></div>');
	el.data('command', command);

	if (function_obj.return_type != Types.VOID) {
		if (!command.variable_value_menu) {
			command.variable_value_menu = [new Models.VariableValueMenu(VariableValueMenu.VAR_OR_VALUE_TYPES.all, null, null, null, true)];
		}
		GenericExpressionManagement.renderExpression(command, function_obj, el.find('.expression_elements'), command.variable_value_menu);
		el.append($('<i class="ui icon unlock button_alternate_expression" style="margin-left: 1rem;"></i>'));

		if (command.lockexpression) {
			if (command.variable_value_menu) {
				try {
					var text = CodeGenerator.elementExpressionCode(command.variable_value_menu);
					if (text) {
						$(el.find('.expression_elements')[0]).toggle();
						$(el.find('.textual_expression')[0]).text(text);
						$(el.find('.textual_expression')[0]).toggle();
						$(el.find('.button_alternate_expression')[0]).toggleClass('unlock').toggleClass('lock');
					}
				} catch (e) {
					command.lockexpression = false;
				}
			}
		}
	} else {
		el.find('.expression_elements').remove();
		command.variable_value_menu = null;
	}
	
	addHandlers(command, function_obj, el);

	return el;
}

function addHandlers (command, function_obj, return_dom) {

	return_dom.find('.button_alternate_expression').on('click', function() {
		if (command.variable_value_menu) {
      var text = CodeGenerator.elementExpressionCode(command.variable_value_menu);
			if (text) {
				$(return_dom.find('.expression_elements')[0]).toggle();
				$(return_dom.find('.textual_expression')[0]).text(text);
				$(return_dom.find('.textual_expression')[0]).toggle();
				$(this).toggleClass('unlock').toggleClass('lock');
				command.lockexpression = !command.lockexpression;
			}
		}
	});

	return_dom.find('.button_remove_command').on('click', function() {
		if (CommandsManagement.removeCommand(command, function_obj, return_dom)) {
			return_dom.fadeOut(400, function() {
				return_dom.remove();
			});
		}
	});
}
