<%
/*
 ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you under the Apache License,
 ~ Version 2.0 (the "License"); you may not use this file except
 ~ in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~ http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing,
 ~ software distributed under the License is distributed on an
 ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ~ KIND, either express or implied.  See the License for the
 ~ specific language governing permissions and limitations
 ~ under the License.
 */

/* Includes */
var log = new Log();
var deviceIdSeperator = "---";
var utils = require('/modules/utils.js');
var carbon = require("carbon");
var HTTPS_TRANSPORT = "https";
var EVENT_PROCESSOR_SERVICE = "/services/EventProcessorAdminService";
var HTTPConstants = Packages.org.apache.axis2.transport.http.HTTPConstants;
var EventProcessorAdminServiceStub = Packages.org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
var eventProcessorAdminServiceWSUrl = utils.getCarbonServerAddress(HTTPS_TRANSPORT) + EVENT_PROCESSOR_SERVICE;
var eventprocessorStub = new EventProcessorAdminServiceStub(eventProcessorAdminServiceWSUrl);
var eventsProcessorServiceClient = eventprocessorStub._getServiceClient();
var eventProcessorOption = eventsProcessorServiceClient.getOptions();
eventProcessorOption.setManageSession(true);
eventProcessorOption.setProperty(HTTPConstants.COOKIE_STRING, session.get('authToken'));
var storeAlerts = require('../include/store_alerts.jag').store; // TODO: change to js
var ws = require('ws');
var process = require("process"), host = process.getProperty('server.host'),
        ip = process.getProperty('carbon.local.ip');
var httpsPort = process.getProperty('mgt.transport.https.proxyPort');
if (!httpsPort) {
    //can use http.port as well
    httpsPort = process.getProperty('mgt.transport.https.port');
}


var verb = request.getMethod();
var executionPlan = request.getParameter('executionPlan');
var queryName = request.getParameter('queryName');
var customName = request.getParameter('customName');
var cepAction = request.getParameter('cepAction'); // i.e 'deploy' new executionPlan , 'edit' executionPlan and etc..
var parseData = request.getParameter('parseData'); // TODO: if app/json use request.getContent()
var deviceId = request.getParameter('deviceId');
var parseDataJson = JSON.parse(parseData);


if (verb == "POST") {
    var path = "../conf/alerts/Geo-ExecutionPlan-" + executionPlan + "_alert.siddhiql";
    var file = new File(path);
    file.open("r");
    var template = "";
    template = file.readAll();
    file.close(); // TODO: use try catch finally  put close inside finally

    for (var parseKey in parseDataJson) {
        parseValue = parseDataJson[parseKey];
        var find = "\\$" + parseKey;
        var re = new RegExp(find, 'g');
        template = template.replace(re, parseValue);
    }

    var updatedTemplate = template;
    log.info(updatedTemplate);

    //commented because theres unwanted characters comes in execution plan
    //var escapedTemplate = escapeSiddhiql(updatedTemplate);


    optionalArgs = {"queryName": queryName, "customName": customName, "executionPlan": executionPlan};
    // TODO: Inefficient if and else if blocks change it by using general keyword to resourceContents
    if (executionPlan == 'Within') {
        var resourceContents = parseDataJson.geoFenceGeoJSON;
    } else if (executionPlan == "Stationery") {
        var resourceContents = parseDataJson;
    } else if (executionPlan == 'Speed') {
        var resourceContents = parseDataJson.speedAlertValue;
    } else if (executionPlan == 'Proximity') {
        var resourceContents = parseDataJson
    } else if (executionPlan == 'Traffic') {
        var resourceContents = parseDataJson.geoFenceGeoJSON;
    }
    storeAlerts(resourceContents, executionPlan, optionalArgs, deviceId);

    var payload;
    if (cepAction == "edit") {
        payload = updatedTemplate;
        var responseJson = {"status": "", "message": ""};
        var result = eventprocessorStub.validateExecutionPlan(payload);
        if (result.equals("success")) {
            try {
                eventprocessorStub.editActiveExecutionPlan(payload, "Geo-ExecutionPlan-" + executionPlan + deviceIdSeperator + deviceId + "_alert");
                responseJson.status = "success";
                responseJson.message = "Query deployed successfully";
            } catch (ex) {
                msg = ex.getMessage();
                responseJson.status = "failed";
                responseJson.message = "Error occurred while deploying the execution plan";
                log.error(msg);
            }
        } else {
            responseJson.status = "failed";
            responseJson.message = "Error occurred while deploying the execution plan";
        }
        print(responseJson);
    } else if (cepAction == "deploy") {
        payload = updatedTemplate;
        var responseJson = {"status": "", "message": ""};
        var result = eventprocessorStub.validateExecutionPlan(payload);
        if (result.equals("success")) {
            try {
                eventprocessorStub.deployExecutionPlan(payload);
                responseJson.status = "success";
                responseJson.message = "Query deployed successfully";
            } catch (ex) {
                msg = ex.getMessage();
                responseJson.status = "failed";
                responseJson.message = "Error occurred while deploying the execution plan";
                log.error(msg);
            }
        } else {
            responseJson.status = "failed";
            responseJson.message = "Error occurred while deploying the execution plan";
        }
        print(responseJson);
    }
}

%>
