'use strict';
define(function(require) {
    return function ($http, $httpParamSerializer) {
        let angular = require('angular');

        return {
            read: function(e) {
                let elements = e;

                if (typeof e == "string") {
                    elements = angular.element(e);
                }

                let data = {};

                elements.each(function(){
                    let element = angular.element(this);

                    data[ element.attr("id") ] = {
                        "name": element.attr("name"),
                        "value": element.val().replace(/&Hat;/g, '^')
                    }
                });

                return data;
            },
            saveNewAtt: function (p) {
                let data = {};

                for (const v of Object.values(p) ) {
                    data[v.name] = JSON.parse(JSON.stringify(v.value).replace(/\^/g, '&Hat;'));
                }

                return $http({
                    url: `/admin/attendance/functions/idm_helper.html?helperType=newAttHelper`,
                    method: "POST",
                    data: $httpParamSerializer(data),
                    headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                });
            },
            saveNewUser: function (p) {
                let data = {};

                for (const v of Object.values(p) ) {
                    data[v.name] = JSON.parse(JSON.stringify(v.value).replace(/\^/g, '&Hat;'));
                }

                return $http({
                    url: `/admin/attendance/functions/idm_helper.html?helperType=newUserHelper`,
                    method: "POST",
                    data: $httpParamSerializer(data),
                    headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                });
            },
            save: function (p) {
                let data = {};

                for (const v of Object.values(p) ) {
                    if (Array.isArray(v.value)) {
                        data[v.name] = JSON.parse(JSON.stringify(v.value.join(",")).replace(/\^/g, '&Hat;'));
                    } else {
                        data[v.name] = JSON.parse(JSON.stringify(v.value).replace(/\^/g, '&Hat;'));
                    }
                    
                }

                let directory = window.location.pathname.split('/')[1];

                return $http({
                    url: `/admin/attendance/functions/idm_helper.html?helperType=changesRecorded`,
                    method: "POST",
                    data: $httpParamSerializer(data),
                    headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }
                });
            }
        }
    }
});