/*
 * Copyright: (c) 2015-2019, Citunius GmbH. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Licence: This program contains proprietary and trade secret information of Citunius GmbH.
 *          Copyright notice is precautionary only and does not evidence any actual or intended 
 *          publication of such program
 *          See: https://www.citunius.de/en/legal
 *
 * Requires: JDK 1.8+
 *
 */

package de.citunius.businesslogic.helloprogramab;

import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import de.citunius.bbp.im.gm.objects.Message;
import de.citunius.bbp.im.gm.objects.PluginReturnMessage;
import de.citunius.bbp.objects.MobileUserAccount;
import de.citunius.businesslogicapi.common.ConstantsCommon;
import de.citunius.businesslogicapi.common.ConstantsPlugin;
import de.citunius.businesslogicapi.common.Utilities;
import de.citunius.businesslogicapi.common.services.LocalisationService;

/**
 * HelloWorld is the main class represents the bot.
 * This service bot interacts with the mobile user and manages all user requests and responses.
 *
 * @author me
 * @version %I%, %G%
 * @since   1.0
*/
public class HelloProgramABBot {
	static Logger logger = Logger.getLogger(MethodHandles.lookup().lookupClass());
	private static String defaultLanguage = "en";
    public static LocalisationService ls = null;
    public String tenantId = null;
    public String accountId = null;
    public HashMap<String, String> pluginMap = null;    
    public String apiId = null;
    public String apiKey = null;
    
    public HelloProgramABBot(String tenantId, String accountId, HashMap<String, String> pluginMap) {
        this.tenantId = tenantId;
        this.accountId = accountId;
        this.pluginMap = pluginMap;
        this.apiId = Utilities.getAttributeFromPropertiesFile(pluginMap, ConstantsCommon.BUSINESSBOTPLATFORM_ACCOUNT_APIID);
        this.apiKey = Utilities.getAttributeFromPropertiesFile(pluginMap, ConstantsCommon.BUSINESSBOTPLATFORM_ACCOUNT_APIKEY);
        ls = new LocalisationService(pluginMap);
    }
        
	/**
	 * Handle incoming instant message from user
	 * 
	 * @param tenantId  the tenant identifier
	 * @param accountId  the account identifier
	 * @param jsonMessage  the message object encoded as JSON
	 * @param jsonMobileUserAccount the mobile user account object encoded as JSON
	 * @return the reply message encoded in JSON format
	 */
	public String handleIncomingMessage(String tenantId, String accountId, String jsonMessage, boolean anonymousUserAccountExists, String jsonAnonymousUserAccount, boolean mobileUserAccountExists, String jsonMobileUserAccount) {		
		logger.info("Plugin: New jsonMessage: ["+jsonMessage+"]");
		String replyMessage = null;
		try {
			JSONObject jsonObjectMessage = new JSONObject(jsonMessage);
			Message message = new Message(jsonObjectMessage);
			MobileUserAccount mobileUserAccount = null;
			if (mobileUserAccountExists) {
				JSONObject jsonObjectMobileUserAccount = new JSONObject(jsonMobileUserAccount);
				mobileUserAccount = new MobileUserAccount(jsonObjectMobileUserAccount);
			}
			logger.info("Plugin: New message: ["+message.getText()+"]");
			logger.info("From UserId: ["+message.getFrom().getId()+"] First-/Lastname: ["+message.getFrom().getFirstName()+" "+message.getFrom().getLastName()+"]");
			logger.info("message text: ["+message.hasText()+"]");
			replyMessage = getAnswer(message.getText());
		} catch(JSONException e) {
			logger.error("JSONException:", e);
		}
		
		String replySubject = ls.getString("Common.DefaultReplySubject", defaultLanguage);
    	return new PluginReturnMessage(replySubject, (replyMessage != null ? replyMessage : "Internal Processing Error"), null).toJson().toString();    	
	}
	
	/**
	 * This function calls program-ab library to get an answer of users request
	 * 
	 * @param request  the user message
	 * @return the response of the bot
	 */
	public String getAnswer(String request) {
		String botname="mybot11"; 
		//String path=System.getProperty("user.dir") + "/resources/ab";xx
		String webInfPath = pluginMap.get(ConstantsPlugin.PLUGIN_SYSTEMDIR);
		String programAbPath = webInfPath + File.separator + pluginMap.get(ConstantsPlugin.PLUGIN_RESOURCE_PATH) + File.separator + "ab";
		
		logger.info("Using programAbPath: "+programAbPath);
		logger.info("This is "+botname.toUpperCase()+" example (Test Case: <Condition> Tag)");
		
		// Create a bot
		Bot bot = new Bot(botname, programAbPath); 
		// Create a client chat sessio
		Chat chatSession = new Chat(bot); 
		// Prepare scanner to read from console
		logger.info("User: ["+request+"]");
		// Chat with the bot - Use the method multisentenceResponse to get the bot's replies to multiple-sentence (one or more sentence) inputs:
		String response = chatSession.multisentenceRespond(request); 
		logger.info("Bot:  ["+response+"]");
	    return response;
	}
	
	/**
	 * Handle incoming request (from system) to send an instant message to the user
	 * 
	 * @param tenantId  the tenant identifier
	 * @param accountId  the account identifier
	 * @param jsonMessage  the message object encoded as JSON
	 * @param jsonFilter  the filter object encoded in JSON used to select the message template 
	 * @param jsonMobileUserAccount the mobile user account object encoded as JSON
	 * @return the reply message encoded in JSON format
	 */
	public String sendTextMessage(String tenantId, String accountId, String jsonMessage, String jsonFilter, boolean anonymousUserAccountExists, String jsonAnonymousUserAccount, boolean mobileUserAccountExists, String jsonMobileUserAccount) {
		String message = "Hello World! (This message was triggered by your business system)";
		PluginReturnMessage pluginReturnMessage = new PluginReturnMessage(null, message, null);
		return pluginReturnMessage.toJson().toString();
    }
	
	/**
	 * Handle incoming callback message from BBP
	 * 
	 * @param tenantId  the tenant identifier
	 * @param accountId  the account identifier
	 * @param message the callback message text (defined during callback setup)
	 * @param jsonMobileUserAccount the mobile user account object encoded as JSON
	 * @return the reply message encoded in JSON format
	 */
	public String handleIncomingCallback(String tenantId, String accountId, String message, boolean anonymousUserAccountExists, String jsonAnonymousUserAccount, boolean mobileUserAccountExists, String jsonMobileUserAccount) {
		PluginReturnMessage pluginReturnMessage = new PluginReturnMessage(null, "Callback message: ["+message+"]", null);
		return pluginReturnMessage.toJson().toString();
	}
}
