/*
 * app.api.js
 * Ajax api helper module
 */

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/
/*global $, io, app */

app.api = (function () {
    'use strict';
    var
        initModule, rockFishVersion, getList, getRelativeList,
        create, get, getName, update, deleteOne,
        deleteRelated, 
        createLicense, getLicenseRequests, generate_from_request, 
        license_email_response,
        search, upsert;


    rockFishVersion = "2.0";

    //************  GENERIC API METHODS *****************
    //
    //GetList
    //
    //route:  app.get('/api/:obj_type/list', function (req, res) {
    getList = function (objType, sortField, callback) {
        var srt = '';
        if (sortField) {
            srt = '?sortBy=' + sortField;
        }
        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/list' + srt,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End get list


    //GetRelativeList
    //
    //route:  app.get('/api/:obj_type/list', function (req, res) {  
    //sortDir: one of 'a' (scending) or 'd' (escending)  
    getRelativeList = function (objType, sortField, sortDir, masterFieldName, masterId, callback) {
        var params = '';

        params = '?masterField=' + masterFieldName + '&masterId=' + masterId;

        if (sortField) {
            params = params + '&sortBy=' + sortField;
            if (sortDir) {
                params = params + '&sortDir=' + sortDir;
            }
        }
        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/relativelist' + params,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End getRelativeList


    //Create
    //
    //Route app.post('/api/:obj_type/create', function (req, res) {
    create = function (objType, objData, callback) {
        $.ajax({
            method: "post",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/create',
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(objData),
            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End create


    //Get
    //
    //route: app.get('/api/:obj_type/read/:id', function (req, res) {
    get = function (objType, objId, callback) {
        var getRoute = '';
        if (objId) {
            getRoute = app.shell.stateMap.apiUrl + objType + '/read/' + objId;
        } else {
            getRoute = app.shell.stateMap.apiUrl + objType + '/read';
        }

        $.ajax({
            method: "GET",
            dataType: "json",
            url: getRoute,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End get

    //getName
    //just like get but only returns name field (plus _id)
    //route: app.get('/api/:obj_type/read/:id', function (req, res) {
    getName = function (objType, objId, callback) {
        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/readName/' + objId,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End get


    //Update
    //
    //route: app.post('/api/:obj_type/update/:id', function (req, res) {
    update = function (objType, objData, callback) {
        var theId;
        if (!objData._id) {
            return callback({
                error: 1,
                msg: 'app.api.js::update->Error: missing _id field in update document',
                error_detail: objData
            });
        }
        theId = objData._id;
        delete objData._id;
        $.ajax({
            method: "post",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/update/' + theId,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(objData),
            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End update

    //----------------------------------------------------
    //UPSERT
    //
    //route: app.post('/api/:obj_type/upsert', function (req, res) {       
    upsert = function (objType, objData, callback) {
        var theId;
        if (objData._id) {
            return callback({
                error: 1,
                msg: 'app.api.js::upsert->Error:has _id field in update document, did you mean to call update instead?',
                error_detail: objData
            });
        }

        $.ajax({
            method: "post",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/upsert',
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(objData),
            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End update


    //DeleteOne
    //
    //app.get('/api/:obj_type/delete/:id', function(req, res) {
    deleteOne = function (objType, objId, callback) {
        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/delete/' + objId,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End get


    //deleteRelated
    //Delete docs in collection that have the indicated field and value
    //
    //route:  app.get('/api/:obj_type/deleterelated', function(req, res) {
    deleteRelated = function (objType, masterFieldName, masterId, callback) {
        var params = '?masterField=' + masterFieldName + '&masterId=' + masterId;

        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + objType + '/deleterelated' + params,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End deleteRelated


    //Search
    //
    //route:  app.get('/api/search?query=querytext', function (req, res) {
    search = function (query, callback) {


        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + 'search?query=' + query,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End search

    ///////////////////////////////////////////////
    //License
    //
    //Route app.post('/api/license/create', function (req, res) {
    createLicense = function (objData, callback) {
        $.ajax({
            method: "post",
            dataType: "text",
            url: app.shell.stateMap.apiUrl + 'license/generate',
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(objData),
            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }

    /////////////////////////////////
    //getLicenseRequests
    //Fetch license requests
    //route: app.get('/api/license/requests', function (req, res) {
    getLicenseRequests = function (callback) {
        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + 'license/requests',
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End get

    /////////////////////////////////
    //generate_from_request
    //Fetch generated response to license request
    //route: app.get('/api/license/generate_from_request/:uid', function (req, res) {
    generate_from_request = function (uid, callback) {
        $.ajax({
            method: "GET",
            dataType: "json",
            url: app.shell.stateMap.apiUrl + 'license/generate_from_request/' + uid,
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },

            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }
    //End get

     ///////////////////////////////////////////////
    //Email license request response
    //
    //app.post('/api/license/email_response', function (req, res) {
    license_email_response = function (objData, callback) {
        $.ajax({
            method: "post",
            dataType: "text",
            url: app.shell.stateMap.apiUrl + 'license/email_response',
            headers: {
                'x-access-token': app.shell.stateMap.user.token
            },
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(objData),
            success: function (data, textStatus) {
                callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                callback({
                    error: 1,
                    msg: textStatus + '\n' + errorThrown,
                    error_detail: {}
                });
            }
        });
    }


    //End license




    //
    //************  /GENERIC API METHODS *****************


    // ***********  SPECIFIC API METHODS ******************
    //so far none required

    initModule = function () { };

    return {
        initModule: initModule,
        rockFishVersion: rockFishVersion,
        getList: getList,
        create: create,
        get: get,
        getName: getName,
        update: update,
        getRelativeList: getRelativeList,
        deleteOne: deleteOne,
        deleteRelated: deleteRelated,
        createLicense: createLicense,
        getLicenseRequests: getLicenseRequests,
        generate_from_request: generate_from_request,
        license_email_response: license_email_response,
        search: search,
        upsert: upsert

    };
}());