/**
 * Created by khuongdt on 12/14/2015.
 * Author : khuongdt
 * Copyright @ 2015 by OneSoft.,JSC
 */

goog.require('com.onesoft.livetube.entity.CSListTypeCardMobile');
goog.require('com.onesoft.livetube.entity.CSTranslateToCard');
goog.require('com.onesoft.livetube.entity.SCTranslateToCard.ResponseCodes');

angular.module('livetube.bonus', ['ngRoute', 'vcRecaptcha', 'ngLoadingSpinner'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/bonus', {
            templateUrl: 'partials/bonus.html',
            controller: 'BonusCtrl'
        });
    }])
    .controller('BonusCtrl', function ($rootScope, $scope, $location, $routeParams, $window, ltSession, authService, vcRecaptchaService){

        $scope.providers = [];
        $scope.errors =[];
        $scope.listCardValues = [];
        $scope.card ={
            providerId:0,
            value:0
        };
        $scope.success =false;

        $scope.response = null;
        $scope.widgetId = null;
        $scope.gRecaptcha = {
            key: '6LcjGRMTAAAAAEIiwp9vqHFre3ul5zFeJFaPSU7y'
        };


        $scope.init = function(){
            goog.events.unlisten(ltSession, com.onesoft.livetube.net.SessionHandler.EventTypes.MESSAGE, $scope.onMessage, false, this);
            goog.events.listen(ltSession, com.onesoft.livetube.net.SessionHandler.EventTypes.MESSAGE, $scope.onMessage, false, this);

            if (!authService.isLoggedIn()) {
                $rootScope.$emit(com.onesoft.livetube.events.EventTypes.REQUEST_LOGIN, {returnUrl: '/bonus'});
                $location.path('/login');
            }
            var req = new com.onesoft.livetube.entity.CSListTypeCardMobile();
            ltSession.getCurrentConnection().sendMessage(req);
        };

        $scope.onMessage = function(e){
            var msg = e.message;
            switch (parseInt(msg.tag)) {
                case com.onesoft.livetube.base.LiveTag.SC_LIST_TYPE_CARD_MOBILE:
                    $scope.providers = msg.getTypeCardMobiles();
                    $rootScope.spinnerActive = true;
                    $scope.spinnerActive = true;

                    $scope.$apply();
                    break;
                case com.onesoft.livetube.base.LiveTag.SC_TRANSLATE_TO_CARD:
                    switch (parseInt(msg.getResponseCode())){
                        case com.onesoft.livetube.entity.SCTranslateToCard.ResponseCodes.TRANSLATE_TO_CARD_CURRENT_TVANG_UNSUCCESS:
                            $scope.errors.push('Bạn không đủ vàng để đổi thưởng.');
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCTranslateToCard.ResponseCodes.TRANSLATE_TO_CARD_MAX_VALUE_UNSUCCESS:
                            $scope.errors.push('Bạn đã đổi quá giới hạn trong ngày.');
                            $scope.$apply();
                            break;
                        case com.onesoft.livetube.entity.SCTranslateToCard.ResponseCodes.UPDATE_SUCCESS:
                            $scope.card.cardNumber = msg.getCardNumber();
                            $scope.card.pinCode = msg.getSeri();
                            $scope.success =true;
                            $scope.$apply();
                            break;

                    }
                    $rootScope.spinnerActive = true;
                    $scope.spinnerActive = true;

                    //$scope.$apply();
                    break;
                case com.onesoft.livetube.base.LiveTag.SC_LIST_CARD_MOBILE:
                    $scope.listCardValues= msg.getListCardMobiles();
                    $scope.$apply();
                    break;
            }
        };

        $scope.getListCardValues = function(providerId, providerName){

            $scope.card.providerName = providerName;
            var req = new com.onesoft.livetube.entity.CSListCardMobile();
            req.setTypeCardMobileId(providerId);
            ltSession.getCurrentConnection().sendMessage(req);
        }

        $scope.setResponse = function (response) {
            $scope.response = response;
        };
        $scope.setWidgetId = function (widgetId) {
            $scope.widgetId = widgetId;
        };
        $scope.cbExpiration = function() {
            $scope.response = null;
        };

        $scope.setCard = function(card){
            $scope.card.mobileCard = card;
            $scope.card.value = card.getId();
        };

        $scope.sendExchange = function(){
            var req = new com.onesoft.livetube.entity.CSTranslateToCard();
            req.setCardMobileId($scope.card.value);
            ltSession.getCurrentConnection().sendMessage(req);
        };


        $scope.submit = function (e) {
            $scope.errors=[];
            var valid = false;
            if($rootScope.captchaEnable && $scope.response ==null){
                $scope.errors.push('Xin hãy xác thực!');
                return;
            }
            if($scope.card.providerId >0 && $scope.card.value  > 0){

            }else{
                $scope.errors.push('Xin hãy chọn nhà cung cấp và mệnh giá thẻ muốn đổi!');
                return;
            }

            //kiểm tra số lượng tiền vàng hiện có && mệnh giá thẻ muốn đổi
            var user =$rootScope.user;
            var card = $scope.card.mobileCard;
            if(card.getValueTvang() >  user.getCurrentTvang()){
                $scope.errors.push('Bạn không đủ tiền để đổi.')
                return;
            }
            /**
             * SERVER SIDE VALIDATION
             *
             * You need to implement your server side validation here.
             * Send the reCaptcha response to the server and use some of the server side APIs to validate it
             * See https://developers.google.com/recaptcha/docs/verify
             */
            console.log('sending the captcha response to the server', $scope.response);
            $scope.sendExchange();
            if (valid) {
                console.log('Success');
            } else {
                console.log('Failed validation');
                // In case of a failed validation you need to reload the captcha
                // because each response can be checked just once
                vcRecaptchaService.reload($scope.widgetId);
            }
        };

    });