/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*global Class, MP_SITE_URL, angular*/
'use strict';
/*
 * Service for autocomplete
 *
 **/

/**
 * TODO
 *
 * this is a copy of autocomplete from reports app
 *
 * REFACTOR both and make them as a common lib
 *
 */

var AutocompleteServiceClass = Class.extend({
    AUTOCOMPLETE_URL           : MP_SITE_URL + '/autocomplete/load',
    AUTOCOMPLETE_VARIABLES_URL : MP_SITE_URL + '/autocomplete/variables',
    AUTOCOMPLETE_INVENTORYVARIABLESLIST_URL : MP_SITE_URL + '/autocomplete/inventoryvariableslist',

    /**
     * @param <string> inputType    - host, promise, bundle
     * @param <string> inputValue   - hostname(ubuntu1)
     * @param <string> inputParentValue - in case autocomplete depends on parent value
     */
    load: function (inputType, inputValue, inputParentType, inputParentValue) {
        var  url = '', dataObj = {};

        dataObj = {'type': inputType, 'value': inputValue};


        if (inputParentType)
        {
            dataObj.parentType = inputParentType;
        }

        if (inputParentValue)
        {
            dataObj.parentValue = inputParentValue;
        }

        url = this.AUTOCOMPLETE_URL;

        return this.$http.post(url, dataObj, {
            cache: false
        }).then(
            function (result) {
                if (result.data.length>0)
                {
                    return result.data;
                }
                else {
                    return ["No Match Found"];
                }

            },
            function (error) {
                // TODO: Notify about error
                return [];
            }
        );
    }

});

(function () {
    var autocompleteServiceProvider = Class.extend({
        instance: new AutocompleteServiceClass(),
        $get: ['$http', function ($http) {
            this.instance.$http = $http;
            return this.instance;
        }]
    });

    angular.module('autocompleteServiceModule', [])
        .provider('autocompleteService', autocompleteServiceProvider);
}());