/**
 *
 * PVA Address Book functionality
 *
 * JS API for PVA Address Book
 *
 *
 * PVA Address Book API Public Methods
 *
 *  + createContact ({contact json}, queryToken, callback);
 *  + searchContacts ({searchString: "a"}, callback);
 *  + mapAddressesToContacts ({phonenumbers: ["",""...], emails: ["", ""...]}, callback);
 *      => given emails, phonenumbers, (+others TBD, e.g. SNS), callback will return JSON list of contacts keyed by identifier
 *
 *
 * @class pvaAddressBookApi
 * @implements NabAPI
 *
 */

newbay.api.PvaABApi = (function (){

    var _prevContact = null,
        _contactInfo = {};

    _prepContact = function (contact) {
        var contact, dict, phoneType, emailType, val;

        // modifications to the 'contact' object model are required to keep compatibility
        //   with recent changes to SAB 2.0 API (2011-08-23)
        // - changes include:
        //   - rename 'contact.fullName' => 'contact.displayName'
        //   - rename 'contact.tel' => 'contact.phone'
        //   - rename 'contact.phone.<type>' => 'contact.phone.<type>.$'
        //   - rename 'contact.email.<type>' => 'contact.email.<type>.$'

        // no full name in PVAB so need to append first & last;
        if (typeof(contact.givenName) !== "undefined" && typeof(contact.familyName) !== "undefined") {
            contact.displayName = contact.givenName + " " + contact.familyName;
        }

        // modify 'phone' values to the updated object model, and cleanup
        if (typeof(contact.phone) === "undefined" && typeof(contact.tel) !== "undefined" ) {
            dict = contact.phone = contact.tel;
            delete contact.tel;

            //
            for (phoneType in dict) {
                if (dict.hasOwnProperty(phoneType)) {
                    val = dict[phoneType];
                    dict[phoneType] = (val && val.$) ? val : { "$": val };
                }
            }
        }

        // modify 'email' values to the updated object model
        dict = contact.email;
        for (emailType in dict) {
            if (dict.hasOwnProperty(emailType)) {
                val = dict[emailType];
                dict[emailType] = (val && val.$) ? val : { "$": val };
            }
        }

        return contact;
    }

    return {

        getSelectedContact : function(callback){
            $.each(_contactInfo, callback);
        },

        addNewContact  : function(param, tokens, callback){

            PvaAPI.createContacts(param, tokens ,{
                onSuccess: function(response){
                    callback.onSuccess(response);
                },
                onFailure: function(response){
                    callback.onFailure(response);
                }
            });

        },

        editContact : function(params, tokens, callback){

            PvaAPI.updateContact(params, tokens,{
                onSuccess: function(response){
                    callback.onSuccess(response);
                },
                onFailure: function(response){
                    callback.onFailure(response);
                }
            });
        },

        deleteContact : function(param, callback){
            //get the number of contacts that have to be deleted
            var contacts = param.length, successDeletes = 0;

            for(var i = 0; i < contacts; i++){

                PvaAPI.deleteContact({"contact.id" : param[i].id}, {

                    onSuccess: function(){

                        successDeletes++;
                        //only call the callback when all are deleted
                        if(contacts == successDeletes){
                            callback.onSuccess();
                        }
                    },
                    onFailure: function(response){
                        callback.onFailure(response);
                    }
                })
            }

        },

        searchContacts : function (param, callback){
            var params = {};
            params.count = 100;     //not supporting pagination of contacts... hence hack attack!

            if (param.searchString) {
                params.q = param.searchString;
            }

            PvaAPI.getContacts(params,{},{
                onSuccess: function(response){

                        var contacts = [];

                        var data = response.responseObject,

                        contactData = data.feed.contacts;

                        //needs to be improved
                        _contactInfo = contactData;

                        for(var key in contactData){
                            if(key.toUpperCase().indexOf(param.searchString.toUpperCase()) == 0){

                                var contact = contactData[key];

                                 //will need to edit the format of the contacts
                                contacts.push( _prepContact( contactData[key] ) );
                            }
                        }

                    callback.onSuccess(contacts);
                 },

                onFailure: function(response){
                    callback.onSuccess([]); //return nothing
                }
            });
        }
    }
})();

