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


var WidgetwizardServiceClass = Class.extend({
        WIDGET_URL: MP_SITE_URL + '/dashboard/widget',

        _postWrapper: function (url, data, cache) {
            return this.$http({
                method: 'POST',
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                url: url,
                data: data,
                cache: cache
            });
        },

        getwidgets: function (widgetId, dashboard = null) {
            var url = this.WIDGET_URL + '/getwidgets/';
            if (widgetId !== undefined && widgetId != null) {
                url += encodeURIComponent(widgetId);
            }

            if (dashboard) {
                url += `?dashboard=${dashboard}`
            }

            return this.$http.get(url, {cache: false});
        },

        getwidgetswithalerts: function (widgetId) {
            var url = this.WIDGET_URL + '/getwidgetswithalerts/';
            if (widgetId !== undefined) {
                url += encodeURIComponent(widgetId);
            }

            return this.$http.get(url, {cache: false});
        },
/*
 * TODO - add common error catch, like:
 *          return this.$http.get(url, {cache: false}).success(function(data, status, headers, config) {
                return data;
            }).fail(function(data, status, headers, config) {
                alert('error');
            });
 */

        savewidget: function (widgetObj) {
            var  url, data;
            url = this.WIDGET_URL + '/savewidget';

            // convert data for post
            data = $.param(widgetObj);
            return this._postWrapper(url, data, false);
        },


        deletewidget: function (widgetId) {
            var url, data;
            url  = this.WIDGET_URL + '/deletewidget';
            data = $.param({'widgetId': widgetId});

            return this._postWrapper(url, data, false);
        },

        reorderwidgets: function (newOrder) {
            var url, data;
            url  = this.WIDGET_URL + '/reorderwidgets';
            data = $.param({'newOrder': newOrder});
            return this._postWrapper(url, data, false);
        }

    });

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

    angular.module('widgetwizardServiceModule', [])
        .provider('widgetwizardService', widgetwizardServiceProvider);
}());