var config = require('config');
var _ = require('lodash');
var Promise = require('bluebird');
var request = Promise.promisifyAll(require("request"));
var parse = require('../../parse');
var apps = require('../../db/apps');
var log = require("../../logger");

module.exports = {
    init: init,
    find: find
}

function init(env) {
    return apps
        .init("code")
        .then(function (ret) {
            env.apps = ret
            return env
        })
}

function getSmaliQuery(query) {
    var queryObj = parse(query);
    var lines = [];
    _.forEach(queryObj, function (v) {
        var line = '';
        _.forEach(v.attributes, function (attrib) {
            if (attrib.name.toLowerCase() == 'class') {
                line += 'L' + attrib.value.replace(/\./g, '/');
            }
            else if (attrib.name.toLowerCase() == 'method') {
                line += ';->' + attrib.value;
            }
        });
        lines.push(line);
    });
    return lines;
}

function find(env, query, options) {
    // If query is not specified, return everything in scope
    if (!query) {
        return Promise.resolve(options.scope);
    }
    var codeQueries = getSmaliQuery(query);
    var queryValue = '_text_:"' + codeQueries.join('" AND _text_:"') + '"'
    // search the code collection in Solr
    function clientError(e) {
        return e.code >= 400 && e.code < 500;
    }

    var solrConfig = config.get("dbConfig.solr");
    var reqURL = "http://" + solrConfig.host + ":" + solrConfig.port +
        "/solr/" + solrConfig.collection + "/query";

    var queryParameters = {q: queryValue, wt: "json"}

    var results = request.getAsync({url: reqURL, qs: queryParameters})
        .get(1)
        .then(function (body) {
            var docs = JSON.parse(body).response.docs;
            return _.pluck(docs, 'id');
        }).catch(clientError, function (e) {
            log.error(e);
        });
    return Promise.resolve(results);
}
@@ -1198,83 +1198,8 @@
 y);%0A
-    var queryValue = '_text_:%22' + codeQueries.join('%22 AND _text_:%22') + '%22'%0A
     
@@ -1472,16 +1472,20 @@
 onfig.co
+deCo
 llection
@@ -1497,25 +1497,24 @@
 query%22;%0A
-%0A
     var 
 queryPar
@@ -1509,53 +1509,289 @@
 var 
-queryParameters = %7Bq: queryValue, wt: %22json%22%7D
+terms = _.map(codeQueries, function (codeQuery) %7B%0A        return '%22' + _escapeSpecialCharacters(codeQuery) + '%22';%0A    %7D);%0A    var _text_ = terms.join(%22 && %22);%0A    var reqObj = %7B%0A        url: reqURL,%0A        qs: %7Bq: %22_text_:%22 + _text_, wt: %22json%22, rows: 1000000000, fl: 'id'%7D%0A    %7D;
 %0A%0A  
@@ -1827,42 +1827,14 @@
 ync(
-%7Burl: reqURL, qs: queryParameters%7D
+reqObj
 )%0A  
@@ -2095,8 +2095,525 @@
 ults);%0A%7D
+%0A%0A/**%0A * Escape a string that uses any of Solr's special characters.%0A * + - && %7C%7C ! ( ) %7B %7D %5B %5D %5E %22 ~ * ? : /%0A * @param str a String that may use any of the meta-characters%0A * @returns %7BString%7D The escaped string with a single backslash proceeding the%0A * special character.%0A * @private%0A */%0Afunction _escapeSpecialCharacters(str) %7B%0A    var escaped = str.replace(/(%5B%5C+%5C-!%5C(%5C)%5C%7B%7D%5C%5B%5C%5D%5C%5E%22~%5C*%5C?:%5C/%5D)/g, '%5C%5C$1');%0A    escaped = escaped.replace(%22&&%22, %22%5C%5C&&%22);%0A    escaped = escaped.replace(%22%7C%7C%22, %22%5C%5C%7C%7C%22);%0A    return escaped;%0A%7D

fix searching solr for multiple code terms