authenticationApp.controller('authenticationCtrl', function ($cordovaLocalNotification,
    $ionicPopup, $ionicLoading, $scope, $location, $window, $rootScope, $ionicPlatform, Auth, $timeout) {

    /*////////////////////  METHOD  ////////////////////*/

    function showLoginForm() {
        var style = {};
        style.opacity = 1;
        $('.login-form-area').animate(style, 500);
    }

    $scope.verifyLogedIn = function () {
        document.getElementById('inputEmail').value = localStorage.getItem("email");
        console.log(localStorage.getItem("login_status"));
        if (localStorage.getItem("login_status") == "1") {
            $ionicPlatform.ready(function () {
                if(cordova){
                    var pushNotification = cordova.require("pushwoosh-cordova-plugin.PushNotification");
                    pushNotification.getLaunchNotification(function (notification) {
                    // neu co pushwoosh
                    if (notification != null) {
                        //alert(JSON.stringify(notification));
                        var user_id = notification.userdata.user_id;
                        var is_room = notification.userdata.is_room == true ? 'true' : '';
                        var url = 'chat.html#/board/chat/' + user_id + '_' + is_room;
                        redirectTo(url);
                    } else { //khong co notification
                        redirectTo('customers.html');
                    }
                })    
                }
                
            })
            redirectTo('customers.html');
        } else {
            $('.login-form-area').fadeIn(500).promise().done(function () {
                showLoginForm();
            });
        }
    }
    $scope.Login = function () {
        $ionicLoading.show({ template: templateLoading });
        var md_pass = forge.md.sha256.create();
        var data_form = {};
        var password = md_pass.update($('#inputPassword').val());
        var email = $('#inputEmail').val();
        data_form = { email: email, password: md_pass.digest().toHex(), action: 'login' };
        $.ajax({
            url: url_site + '/auth',
            type: 'post',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossdomain: true,
            data: data_form
        }).done(function (data, textStatus, xhr) {
            console.log(xhr.getAllResponseHeaders());
            $scope.info = {};
            if (data.status) {
                $scope.info.token = document.getElementById('deviceToken').value;
                $scope.info.device = document.getElementById('devicePlatform').value;
                $scope.info.email = document.getElementById('inputEmail').value;
                console.log($scope.info);
                   localStorage.setItem("login_status", "1");
                    localStorage.setItem("email", $scope.info.email);
                    localStorage.setItem("token", $scope.info.token);
                    localStorage.setItem('departmentId', data.departmentId);
                    localStorage.setItem('currentIdLogin', data.currentIdLogin);
                    localStorage.setItem('role', data.role);
                    localStorage.setItem('cookie', xhr.getResponseHeader("Set-Cookie"));
                 $ionicLoading.hide();
                 var pagedefault = data.pagedefault;
                 Auth.registerDevice($scope.info).success(function(data) {
                    switch(pagedefault){
                      case 'users.html':
                      case 'customers.html':
                      case 'tasks.html':
                      case 'settings.html':
                      case 'pipus.html':
                      redirectTo(pagedefault);
                      break;
                      case 'opportunities.html':
                      redirectTo('opportunity.html');
                      break;
                      case 'appointments.html':
                      redirectTo('scheduleapp.html');
                      break;
                      case 'schedule.html':
                      redirectTo('myschedule.html');
                      break;
                      case 'newfeeds.html':
                      redirectTo('newsfeed.html');
                      break;
                      case 'chats.html':
                      redirectTo('chat.html');
                      break;
                      case 'products.html':
                      redirectTo('pricebook.html');
                      break;
                      case 'paymenthistories.html':
                      redirectTo('payment.html');
                      break;
                      case 'customereviews.html':
                      redirectTo('customers.html?action=review');
                      break;
                      case 'taskfilter.html':
                      redirectTo('tasks.html?action=filter');
                      break;
                      case 'mapinfos.html':
                      redirectTo('map.html');
                      break;
                      default:
                      redirectTo('newsfeed.html');
                      break;
                  }
                 });
               
            } else {
                $ionicLoading.hide();
                messagebox('fail', 'Login failed', 'Your email or password incorrect !<br />Please try again!');
            }
        })
    }

    //Neu co localPush-->redirect
    $rootScope.$on('$cordovaLocalNotification:click',
        function (event, notification, state) {
            var data = JSON.parse(notification.data);
            var user_id = data.user_id;
            var is_room = data.is_room == true ? 'true' : '';
            var url = 'chat.html#/board/chat/' + user_id + '_' + is_room;
            redirectTo(url);
        });
    // ----------------
    $timeout(function () {
        $scope.verifyLogedIn();
    }, 1000)

    window.addEventListener('native.keyboardhide', keyboardHideHandler);
    window.addEventListener('native.keyboardshow', keyboardShowHandler);

    $scope.openKeyboard = function (kh) {
        if ($(window).outerHeight() < 400) {
            $(".login-form-area").addClass('has-keyboard');
        } else {
            $(".login-form-area").css("padding-bottom", kh + "px");
        }
    }

    $scope.closeKeyboard = function () {
        $(".login-form-area").removeClass('has-keyboard').css("padding-bottom", 0);
    }

    function keyboardShowHandler(e) {
        if (isiOs) {
            $scope.openKeyboard(e.keyboardHeight);
        }
    }

    function keyboardHideHandler(e) {
        if (isiOs) {
            $scope.closeKeyboard();
        }
    }
});
