(function(context,$) {

    /**
     * Javascript wrappers for the REST API
     */

    "use strict";

    context.JK = context.JK || {};
    context.JK.Rest = function() {

        var self = this;
        var logger = context.JK.logger;

        function updateSession(id, newSession, onSuccess) {
            logger.debug('Rest.updateSession');
            return $.ajax('/api/sessions/' + id, {
                type: "PUT",
                data : newSession,
                dataType : 'json',
                success: onSuccess
            });
        }


        function getUserDetail(options) {
            var id = getId(options);

            var url = "/api/users/" + id;
            return $.ajax({
                type: "GET",
                dataType: "json",
                url: url,
                async: true,
                processData: false
            });
        }

        function getCities (options) {
            var country = options['country']
            var region = options['region']

            return $.ajax('/api/cities', {
                data : { country: country, region: region },
                dataType : 'json'
            });
        }

        function getRegions(options) {
            var country = options["country"]

            return $.ajax('/api/regions', {
                data : { country: country},
                dataType : 'json'
            });
        }

        function getCountries() {
            return $.ajax('/api/countries', {
                dataType : 'json'
            });
        }

        function getIsps(options) {
            var country = options["country"]

            return $.ajax('/api/isps', {
                data : { country: country},
                dataType : 'json'
            });
        }

        function getInstruments(options) {
            return $.ajax('/api/instruments', {
                data : { },
                dataType : 'json'
            });
        }

        function updateAvatar(options) {
            var id = getId(options);

            var original_fpfile = options['original_fpfile'];
            var cropped_fpfile = options['cropped_fpfile'];
            var crop_selection = options['crop_selection'];

            var url = "/api/users/" + id + "/avatar";
            return $.ajax({
                type: "POST",
                dataType: "json",
                url: url,
                contentType: 'application/json',
                processData:false,
                data: JSON.stringify({
                    original_fpfile : original_fpfile,
                    cropped_fpfile : cropped_fpfile,
                    crop_selection : crop_selection
                })
            });
        }

        function deleteAvatar(options) {
            var id = getId(options);

            var url = "/api/users/" + id + "/avatar";
            return $.ajax({
                type: "DELETE",
                dataType: "json",
                url: url,
                contentType: 'application/json',
                processData:false
            });
        }

        function getFilepickerPolicy(options) {
            var id = getId(options);
            var handle = options && options["handle"];
            var convert = options && options["convert"]

            var url = "/api/users/" + id + "/filepicker_policy";

            return $.ajax(url, {
                data : { handle : handle, convert: convert },
                dataType : 'json'
            });
        }

        function getFriends(options) {
            var id = getId(options);

            return $.ajax({
                type: "GET",
                url: '/api/users/' + id + '/friends',
                dataType: 'json'
            });
        }

        function getClientDownloads(options) {

            return $.ajax({
                type: "GET",
                url: '/api/artifacts/clients',
                dataType: 'json'
            });
        }

        /** check if the server is alive */
        function serverHealthCheck(options) {
            console.log("serverHealthCheck")
            return $.ajax({
                type: "GET",
                url: "/api/versioncheck"
            });
        }

        function getId(options) {
            var id = options && options["id"]

            if(!id) {
                id = context.JK.currentUserId;
            }
            return id;
        }

        function createInvitation(emailAddress, message) {
            return $.ajax({
                type: "POST",
                dataType: "json",
                url: '/api/invited_users',
                contentType: 'application/json',
                processData:false,
                data: JSON.stringify({
                    email : emailAddress,
                    note: message
                })
            });
        }

        function postFeedback(email, body) {
            return $.ajax({
                type: "POST",
                dataType: "json",
                url: '/api/feedback',
                contentType: 'application/json',
                processData:false,
                data: JSON.stringify({
                    email : email,
                    body: body
                })
            });
        }

        function acceptFriendRequest(options) {
            var id = getId(options);
            var friend_request_id = options["friend_request_id"];
            var status = options["status"];

            var friend_request = { status: status };

            var deferred = $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: "/api/users/" + id + "/friend_requests/" + friend_request_id,
                data: JSON.stringify(friend_request),
                processData: false
            });

            deferred.done(function() {
                context.JK.GA.trackFriendConnect(context.JK.GA.FriendConnectTypes.accept);
            });

            return deferred;
        }

        function userDownloadedClient(options) {

            return $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: "/api/users/progression/downloaded_client",
                processData: false
            });
        }

        function userCertifiedGear(options) {

            return $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: "/api/users/progression/certified_gear",
                processData: false,
                data: JSON.stringify({
                    success: options.success,
                    reason: options.reason
                })
            });
        }

        function userSocialPromoted(options) {
            var id = getId(options);

            return $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: "/api/users/progression/social_promoted",
                processData: false
            });
        }

        function signout() {
            return $.ajax({
                type: "DELETE",
                dataType: "json",
                url: '/signout',
                contentType: 'application/json'
            });
        }

        function initialize()  {
            return self;
        }

        // Expose publics
        this.initialize = initialize;
        this.getUserDetail = getUserDetail;
        this.getCities = getCities;
        this.getRegions = getRegions;
        this.getCountries = getCountries;
        this.getIsps = getIsps;
        this.getInstruments = getInstruments;
        this.updateAvatar = updateAvatar;
        this.deleteAvatar = deleteAvatar;
        this.getFilepickerPolicy = getFilepickerPolicy;
        this.getFriends = getFriends;
        this.updateSession = updateSession;
        this.getClientDownloads = getClientDownloads
        this.createInvitation = createInvitation;
        this.postFeedback = postFeedback;
        this.serverHealthCheck = serverHealthCheck;
        this.acceptFriendRequest = acceptFriendRequest;
        this.signout = signout;
        this.userDownloadedClient = userDownloadedClient;
        this.userCertifiedGear = userCertifiedGear;
        this.userSocialPromoted = userSocialPromoted;

        return this;
    };


})(window,jQuery);