/*
goog.require('jQuery');
goog.require('divvy.core');
goog.provide('divvy.client');
*/
divvy.client = divvy.client || {};
divvy.client.SimpleClient = Class.extend(
    {

        default_config: {
            rootUrl:'/api/v2/json',
            alert: divvy.alert,
            errorMessages: {
                "401": "You're not allowed to do that!",
                "404": "We couldn't find what you were looking for."
            }
        },

        /**
         * @class A simple client for divvyshot
         * @constructs
         */
        init: function(config){
            config = jQuery.extend(true, {}, this.default_config, config);
            this.rootUrl = config.rootUrl;
            this.alert = config.alert;
            this.errorMessages = config.errorMessages;
        },

        _getErrorHandler: function(successCallback, messages){
            var self = this;
            messages = jQuery.extend(this.errorMessages, messages || {});
            return function(xhr, textStatus){
                if (xhr.status === 204){
                    //silly jquery... 204 isn't an error!
                    successCallback(null, textStatus);
                } else {
                    self.alert(messages[''+xhr.status] || "Sorry, but it looks like there was an error.");
                }
            };
        },

        _url: function(path){
            var url = path;
            if (url && url.substr(0, this.rootUrl.length) !== this.rootUrl){
                url = this.rootUrl + url;
            }
            return url;
        },

        _getOptions: function(type, extend){
            extend.url = this._url(extend.url);
            return jQuery.extend(
                {
                    dataType: "json",
                    error: this._getErrorHandler(extend.success, extend.errorMessages),
                    type: type
                }, extend || {});
        },
        _delete: function(options){
            jQuery.ajax(this._getOptions("DELETE", options));
        },

        _put: function(options){
            jQuery.ajax(this._getOptions("PUT", options));
        },

        _get: function(options){
            jQuery.ajax(this._getOptions("GET", options));
        },

        _post: function(options){
            jQuery.ajax(this._getOptions("POST", options));
        },

        getEventPhotosUrl: function(eventSlug){
            return this._url('/event/'+eventSlug+'/photo/');
        },
        getEventUrl: function(eventSlug){
            return this._url("/event/"+eventSlug+"/");
        },
        getPhotoUrl: function(photoSlug){
            return this._url("/photo/"+photoSlug+"/");
        },
        getUserUrl: function(userId){
            return this._url("/user/"+userId+"/");
        },

        getPhoto: function(photoSlug, callback){
            this._get(
                {
                    url: this.getPhotoUrl(photoSlug),
                    success: function(photos){
                        callback(photos.length > 0 ? photos[0] : null);
                    }
                });
        },

        getNextPhoto: function(photoSlug, callback){
            this._get(
                {
                    url: this.getPhotoUrl(photoSlug),
                    data: { offset: 'next' },
                    success: function(photos){
                        callback(photos.length > 0 ? photos[0] : null);
                    }
                });
        },

        getPrevPhoto: function(photoSlug, callback){
            this._get(
                {
                    url: this.getPhotoUrl(photoSlug),
                    data: { offset: 'prev' },
                    success: function(photos){
                        callback(photos.length > 0 ? photos[0] : null);
                    }
                });
        },

        getEventPhotos: function(eventSlug, query, callback){
            var params = {};
            if (query.after){
                params.after_timestamp = query.after.getTime();
                delete query.after;
            }
            $.extend(params, query);
            this._get(
                {
                    url: this.getEventPhotosUrl(eventSlug),
                    data: params,
                    success: callback
                });
        },

        deletePhoto: function(photoSlug, callback){
            this._delete(
                {
                    url: this.getPhotoUrl(photoSlug),
                    success: function(data){
                        callback(data.next_url);
                    }
                });
        },

        trashPhoto: function(photoSlug, callback){
            this._put(
                {
                    url: this.getPhotoUrl(photoSlug),
                    data: {trashed: true},
                    success: callback
                });
        },

        flagPhoto: function(photoSlug, flag, callback){
            this._put(
                {
                    url: this.getPhotoUrl(photoSlug),
                    data: {
                        flag: flag
                    },
                    success: callback
                });
        },

        rotatePhoto: function(photoSlug, degrees, callback){
            this._put(
                {
                    url: this.getPhotoUrl(photoSlug),
                    success: callback,
                    data: {degrees: degrees},
                    errorMessages: {
                        "404": "We couldn't find that photo to rotate."
                    }
                });
        },

        renamePhoto: function(photoSlug, newName, callback){
            this._put(
                {
                    url: this.getPhotoUrl(photoSlug),
                    success: function(data){callback(data.name);},
                    data: {name: newName},
                    errorMessages: {
                        "404": "We couldn't find that photo to rename."
                    }
                }
            );
        },

        renameEvent: function(eventSlug, newName, callback){
            this.updateEvent(eventSlug,
                             {name:newName},
                             function(data){
                                 callback(newName);
                             });
        },

        updateEvent: function(eventSlug, data, callback){
            this._put(
                {
                    url: this.getEventUrl(eventSlug),
                    success: callback,
                    data: data
                });
        },

        getEventArchive: function(eventSlug, create, callback){
            this._get(
                {
                    url: this.getEventUrl(eventSlug)+'archive/',
                    success: callback,
                    data: {create:create}
                });
        },
        getEventMembers: function(eventSlug, callback){
            this._get(
                {
                    url: this.getEventUrl(eventSlug)+'member/',
                    success: callback
                });
        },

        sendFriendRequest: function(userId, message, callback){
            this._post(
                {
                    url: this.getUserUrl(userId)+'friends/',
                    success: callback,
                    data: {
                        message: message
                    }
                });
        },

        updateFriendRequest: function(userId, data, callback){
            /**
             * Data is one of:
             *   {accepted: true}
             *   {ignored: true}
             */
            this._put(
                {
                    url: this.getUserUrl(userId)+'friends/',
                    success: callback,
                    data: data
                });
        },

        removeFriend: function(userId, callback){
            this._delete(
                {
                    url: this.getUserUrl(userId)+'friends/',
                    success: callback
                });
        },

        getImportList: function(data, callback){
            /**
             * Data is of the form:
             *   {source: "google",
             *    username: "foo",
             *    password: "bar"}
             * TODO: secure over https
             */
            this._get(
                {
                    url: this._url('/user/import/'),
                    data: data,
                    success: callback
                });
        },

        sendInvitations: function(data, callback){
            /**
             * Data is of the form:
             *   {count: 2,
             *    request_friend_if_exists: "true",
             *    name0: "foo", email0: "foo@bar.com",
             *    name1: "bill",email1: "bill@example.com"}
             */
            this._post(
                {
                    url: this._url('/user/import/'),
                    data: data,
                    success: callback
                });
        },

        getProfile: function(callback){
            this._get(
                {
                    url: this._url('/user/profile/'),
                    success: callback
                });
        },

        updateProfile: function(data, callback){
            /**
             * Update a users profile
             */
            this._put(
                {
                    url: this._url('/user/profile/'),
                    data: data,
                    success: callback
                });
        }

    });

divvy.client.newSimpleClient = function(config){
    return new divvy.client.SimpleClient(config);
};


divvy.client.SimpleDwedsClient = divvy.client.SimpleClient.extend(
    {
        inviteGuest: function(guestId, callback){
            this._put(
                {
                    url: '/guest/'+guestId+'/',
                    success: callback,
                    data: {send_invite: true}
                });
        },

        deleteGuest: function(guestId, callback){
            this._delete(
                {
                    url: '/guest/'+guestId+'/',
                    success: callback
                });
        },

        checkWeddingExists: function(weddingSlug, callback){
            var self = this;

            function successHandler(){
                callback(true);
            }
            function errorHandler(xhr, textStatus){
                if (xhr.status === 404){
                    callback(false);
                } else {
                    self._getErrorHandler(successHandler)(xhr, textStatus);
                }
            }

            this._get(
                {
                    url: '/wedding/'+weddingSlug+'/',
                    success: successHandler,
                    error: errorHandler
                });
        }
    });

divvy.client.newSimpleDwedsClient = function(config){
    return new divvy.client.SimpleDwedsClient(config);
};
