var app = angular.module("Weight", []);
app.controller("WeightController",  function ($scope, weightService) {
        $scope.newWeight = 0.0;

        $scope.weightData = [];

        $scope.submitForm = function () {
            "use strict";
            console.log('Submitting..');
            console.log($scope.newWeight);
            $http({method: 'post', url: '/weight', params: {weight: $scope.newWeight}});
        };

        loadRemoteData();

        function applyRemoteData(newData) {
            $scope.weightData = newData;
        }

        function loadRemoteData() {
            weightService.getWeight()
                .then(
                    function (weightData) {
                        applyRemoteData(weightData);
                    }
                )
        }

    }
);

app.service(
    "weightService",
    function ($http, $q) {
        return ({getWeight: getWeight});

        function getWeight() {
            var request = $http({
                method: "get",
                url: "/weight/all",
                params: {
                    /* action:"get"*/
                }
            });
            return (request.then(handleSuccess, handleError));
        }

        function setWeight(w) {
            "use strict";

            $http({method: 'post', url: '/weight', params: {weight: w}});

        }

        function handleError(response) {
            if (!angular.isObject(response.data) || !response.data.message) {
                return ( $q.reject("An unknown error occured"));
            }

            return ($q.reject(response.data.message));
        }

        function handleSuccess(response) {
            return (response.data);
        }

    }
);