/*
 * Copyright (c) Vidimax 2011.
 */

var Api = function(){

    var API_URL = 'https://api-serv.vidimax.ru:444/vidimax-api';

    var url_actions = {
        "ping": "/json/2.0/ping",
        "requestActivation": "/web/2.0/requestActivation",
        "confirmActivation": "/web/2.0/confirmActivation",
        "login": "/web/2.0/login",
        "logout": "/web/2.0/logout",
        "checkLogin": "/web/2.0/checkLogin",
        "getContent": "/web/2.0/getContent",
        "getVideoUrl": "/web/2.0/getVideoUrl",
        "listContentSpecial": "/json/2.0/listContentSpecial",
        "registerContentAction": "/web/2.0/registerContentAction"
    };

    var defaultAjaxOptions = {
        async: true,
        dataType: 'jsonp',
        type: 'GET'
    };

    var _lastResultCode = null;
    var _lastResultMessage = null;
    var _isLoggedIn = false;
    var _ping = false;

    function getActionUri(actionName) {
        if (url_actions[actionName])
            return url_actions[actionName];
        else
            return "";
    }

    function getActionUrl(actionName) {
        return API_URL + getActionUri(actionName);
    }

    var CALL_TIMEOUT_MSEC = 5000;
    var callTimeout = null;

    function onCallTimeout(onError) {
        globalVidimaxAjaxCompleteHandler();
        debug("onCallTimeout");
        if (typeof onError == "function") {
            onError();
        }
    }

    function setCallTimeout(onError) {
        if (callTimeout != null) {
            debug("CallTimeout already set");
            clearTimeout(callTimeout);
        }
        debug("setCallTimeout");
        callTimeout = setTimeout(function (){onCallTimeout(onError)}, CALL_TIMEOUT_MSEC);
    }

    function clearCallTimeout() {
        if (callTimeout != null) {
            debug("clearCallTimeout");
            clearTimeout(callTimeout);
        } else {
            debug("CallTimeout already clean");
        }
    }

    function call(_options, actionName, parameters, onSuccess, onError) {
        var options = $.extend({}, defaultAjaxOptions, {
            url: getActionUrl(actionName),
            data: parameters,
            success: function (response) {
                clearCallTimeout();
                if (response) {
                    _lastResultCode = response.resultCode;
                    _lastResultMessage = response.resultMessage;
                } else {
                    _lastResultCode = null;
                    _lastResultMessage = null;
                }
                if (typeof onSuccess == "function") {
                    onSuccess(response);
                }
            },
            error: function () { // не запускается в случае jsonp
                clearCallTimeout();
                _lastResultCode = null;
                _lastResultMessage = null;
                if (typeof onError == "function") {
                    onError();
                }
/*
            },
            complete: function() {
                debug("Api call complete");
*/
            }
        }, _options);
        $.ajax(options);
        if (options.dataType == 'jsonp') {
            // в случае jsonp запускаем таймаут на случай неответа сервера Api
            setCallTimeout(onError);
        }
    }

    function callSync(actionName, parameters, onSuccess, onError) {
        call({async: false}, actionName, parameters, onSuccess, onError)
    }

    function callAsync(actionName, parameters, onSuccess, onError) {
        call({}, actionName, parameters, onSuccess, onError)
    }

    return {

        init: function (apiUrl) {
            if (apiUrl && apiUrl != "") {
                API_URL = apiUrl;
            }
        },

        requestActivation: function (phoneNumber, promoCode, callbackResultOk, callbackBadResult, callbackError) {
            debug("[requestActivation] requestActivation for " + phoneNumber);
            callAsync("requestActivation", {
                "phoneNumber": phoneNumber,
                "promoCode": promoCode
            }, function(response){
                debug("[requestActivation] response.resultCode = " + response.resultCode);
                _isLoggedIn = response.resultCode == 0;
                if (_isLoggedIn) {
                    if (typeof callbackResultOk == "function") callbackResultOk(response);
                } else {
                    debug("[requestActivation] response.resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                }
            }, function(){
                debug("[requestActivation] error");
                _isLoggedIn = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        requestActivationExisted: function (activationCode, pinCode, phoneNumber, promoCode, callbackResultOk, callbackBadResult, callbackError) {
            debug("[requestActivation] requestActivation for " + phoneNumber);
            callAsync("requestActivation", {
                "activationCode": activationCode,
                "pinCode": pinCode,
                "phoneNumber": phoneNumber,
                "promoCode": promoCode
            }, function(response){
                debug("[requestActivation] response.resultCode = " + response.resultCode);
                _isLoggedIn = response.resultCode == 0;
                if (_isLoggedIn) {
                    if (typeof callbackResultOk == "function") callbackResultOk(response);
                } else {
                    debug("[requestActivation] response.resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                }
            }, function(){
                debug("[requestActivation] error");
                _isLoggedIn = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        confirmActivation: function (phoneNumber,
                                     activationPin,
                                     firstName,
                                     lastName,
                                     email,
                                     birthDate,
                                     callbackResultOk, callbackBadResult, callbackError) {
            debug("[confirmActivation] confirmActivation for " + phoneNumber);
            callAsync("confirmActivation", {
                "phoneNumber": phoneNumber,
                "activationPin": activationPin,
                "firstName": firstName,
                "lastName": lastName,
                "email": email,
                "birthDate": birthDate
            }, function(response){
                debug("[confirmActivation] response.resultCode = " + response.resultCode);
                _isLoggedIn = response.resultCode == 0;
                if (_isLoggedIn) {
                    if (typeof callbackResultOk == "function") callbackResultOk(response);
                } else {
                    debug("[confirmActivation] response.resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                }
            }, function(){
                debug("[confirmActivation] error");
                _isLoggedIn = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        login: function (username, password, callbackLoggedIn, callbackNotLoggedIn, callbackError) {
            debug("[login] start login as " + username);
            callAsync("login", {
                "username": username,
                "password": password,
                "rememberMe": true
            }, function(response){
                debug("[login] response.resultCode = " + response.resultCode);
                _isLoggedIn = response.resultCode == 0;
                if (_isLoggedIn) {
                    if (typeof callbackLoggedIn == "function") callbackLoggedIn(response);
                } else {
                    debug("[login] response.resultMessage = " + response.resultMessage);
                    if (typeof callbackNotLoggedIn == "function") callbackNotLoggedIn(response);
                }
            }, function(){
                debug("[login] error");
                _isLoggedIn = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        checkLogin: function (callbackLoggedIn, callbackNotLoggedIn, callbackError) {
            debug("[checkLogin] start ");
            callAsync("checkLogin", {}, function(response){
                _isLoggedIn = response.resultCode == 0;
                debug("[checkLogin] response.resultCode = " + response.resultCode);
                if (_isLoggedIn) {
                    if (typeof callbackLoggedIn == "function") callbackLoggedIn(response);
                } else {
                    debug("[checkLogin] response.resultMessage = " + response.resultMessage);
                    if (typeof callbackNotLoggedIn == "function") callbackNotLoggedIn(response);
                }
            }, function(){
                debug("[checkLogin] error ");
                _isLoggedIn = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        logoutNow: function () {
            debug("[logout] start ");
            $(document).append("<img src=\"" + getActionUrl("logout") + "\">");
            debug("[logout] start done");
        },

        logout: function (callbackLoggedOut, callbackNotLoggedOut, callbackError) {
            debug("[logout] start ");
            callAsync("logout", {}, function(response){
                _isLoggedIn = !response.resultCode == 0;
                debug("[logout] response.resultCode = " + response.resultCode);
                if (response.resultCode == 0) {
                    if (typeof callbackLoggedOut == "function") callbackLoggedOut(response);
                } else {
                    debug("[logout] response.resultMessage = " + response.resultMessage);
                    if (typeof callbackNotLoggedOut == "function") callbackNotLoggedOut(response);
                }
            }, function(){
                debug("[logout] error ");
                if (typeof callbackError == "function") callbackError();
            });
        },

        ping: function (callbackPingOk, callbackPingError, callbackError) {
            debug("[ping] start ");
            callAsync("ping", {}, function(response){
                _ping = response.resultCode == 0;
                debug("[ping] resultCode = " + response.resultCode);
                if (response.resultCode == 0) {
                    if (typeof callbackPingOk == "function") callbackPingOk(response);
                } else {
                    debug("[ping] resultMessage = " + response.resultMessage);
                    if (typeof callbackPingError == "function") callbackPingError(response);
                }
            }, function(){
                debug("[ping] error ");
                _ping = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        getContent: function (contentId, callbackResult, callbackBadResult, callbackError) {
            debug("[getContent] start ");
            callAsync("getContent", {"contentId": contentId}, function(response){
                _ping = response.resultCode == 0;
                debug("[getContent] resultCode = " + response.resultCode);
                if (response.resultCode == 0) {
                    if (typeof callbackResult == "function") callbackResult(response.contentInfo);
                } else {
                    debug("[getContent] resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                    /**
                     * resultCode = -25
                     * resultMessage = Video file not found
                     */
                }
            }, function(){
                debug("[getContent] error ");
                _ping = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        getVideoUrl: function (contentId, callbackResult, callbackBadResult, callbackError) {
            debug("[getVideoUrl] start ");
            callAsync("getVideoUrl", {"contentId": contentId}, function(response){
                _ping = response.resultCode == 0;
                debug("[getVideoUrl] resultCode = " + response.resultCode);
                if (response.resultCode == 0) {
                    if (typeof callbackResult == "function") callbackResult(response.url);
                } else {
                    debug("[getVideoUrl] resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                    /**
                     * resultCode = -25
                     * resultMessage = Video file not found
                     */
                }
            }, function(){
                debug("[getVideoUrl] error ");
                _ping = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        registerContentAction: function (contentId, action, callbackResult, callbackBadResult, callbackError) {
            debug("[registerContentAction] start ");
            callAsync("registerContentAction", {"contentId": contentId, "action": action}, function(response) {
                _ping = response.resultCode == 0;
                debug("[registerContentAction] resultCode = " + response.resultCode);
                if (response.resultCode == 0) {
                    if (typeof callbackResult == "function") callbackResult();
                } else {
                    debug("[registerContentAction] resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                    /**
                     * resultCode = -25
                     * resultMessage = Video file not found
                     */
                }
            }, function(){
                debug("[registerContentAction] error ");
                _ping = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        addWishList: function (contentId, callbackResult, callbackBadResult, callbackError) {
            debug("[addWishList] start ");
            this.registerContentAction(contentId, "addWishList", callbackResult, callbackBadResult, callbackError);
        },

        delWishList: function (contentId, callbackResult, callbackBadResult, callbackError) {
            debug("[delWishList] start ");
            this.registerContentAction(contentId, "delWishList", callbackResult, callbackBadResult, callbackError);
        },

        startWatch: function (contentId, callbackResult, callbackBadResult, callbackError) {
            debug("[startWatch] start ");
            this.registerContentAction(contentId, "startWatch", callbackResult, callbackBadResult, callbackError);
        },

        finishWatch: function (contentId, callbackResult, callbackBadResult, callbackError) {
            debug("[finishWatch] start ");
            this.registerContentAction(contentId, "finishWatch", callbackResult, callbackBadResult, callbackError);
        },

//        "nodeId=MOVIES&groupId=top",
//        "nodeId=MOVIES&groupId=new",
//        "nodeId=MOVIES&groupId=recom"

        listContentSpecial: function (nodeId, groupId, callbackResult, callbackBadResult, callbackError) {
            debug("[listContentSpecial] start ");
            callAsync("listContentSpecial", {"nodeId": nodeId, "groupId": groupId}, function(response){
                _ping = response.resultCode == 0;
                debug("[listContentSpecial] resultCode = " + response.resultCode);
                if (response.resultCode == 0) {
                    if (typeof callbackResult == "function") callbackResult(response.content);
                } else {
                    debug("[listContentSpecial] resultMessage = " + response.resultMessage);
                    if (typeof callbackBadResult == "function") callbackBadResult(response);
                }
            }, function(){
                debug("[listContentSpecial] error ");
                _ping = false;
                if (typeof callbackError == "function") callbackError();
            });
        },

        getMoviesTop: function (callbackResult, callbackBadResult, callbackError) {
            debug("[getMoviesTop] start ");
            this.listContentSpecial("MOVIES", "top", callbackResult, callbackBadResult, callbackError);
        },

        getMoviesNew: function (callbackResult, callbackBadResult, callbackError) {
            debug("[getMoviesNew] start ");
            this.listContentSpecial("MOVIES", "new", callbackResult, callbackBadResult, callbackError);
        },

        getMoviesRecom: function (callbackResult, callbackBadResult, callbackError) {
            debug("[getMoviesRecom] start ");
            this.listContentSpecial("MOVIES", "recom", callbackResult, callbackBadResult, callbackError);
        }

    }

}();

