var apendoCtrls = angular.module('apendoCtrls', []);
var logged = false;
apendoCtrls.controller('MainCtrl', function($scope, $timeout, $location, $window){
    $window.updateNavBar('Public');
    $scope.obj = {};
    $scope.updateMessage = function(message, clear) {
        $timeout(function(){
            $scope.obj = $scope.obj || {};
            $scope.obj.message = message;
            if (message && clear) {
                $timeout(function(){
                    $scope.obj.error = false;
                    $scope.updateMessage('');
                }, 1000);
            }
        });
    }
    $scope.login = function() {
        var options = {};
        options.username = $scope.username;
        options.password = $scope.password;
        LT17.register('userLoggedIn', function(result){
            LT17.unregister('userLoggedIn');
            if (result.success) {
                $scope.updateMessage('');
                $scope.error = false;
                $location.path('/drop');
                return;
            }
            $scope.obj.error = true;
            $scope.updateMessage('User atau password Anda salah.', true);
        });
        $('form input').blur();
        Apendo.userLogin(options);
        $scope.updateMessage('Mencoba masuk...');

        LT17.register('checkingProxy', function(){
            LT17.unregister('checkingProxy');
            $scope.updateMessage('Mengecek proxy...');
        });

        LT17.register('checkingProxyDone', function(type){
            LT17.unregister('checkingProxyDone');
            $scope.updateMessage('Selesai mengecek proxy...');
        });
    }
    if (logged) {
        Apendo.userLogout({});
    }
    // not accepting drops here
    Apendo.parentAcceptDrops({acceptDrops : false});
});

apendoCtrls.controller('DropCtrl', function($scope, $timeout, $sce, $window){
    $window.updateNavBar('User');
    var messages = {
        nothing : "<b><i>Copy-Paste</i> atau <i>Drag</i> token dari SPSE ke sini</b>",
        ready : "<b>Letakkan di mana saja.</b>",
        dropped : "<b>Token</b>",
        sending : "<b>Mengirim token...</b>",
        failed : "<b>Terjadi kesalahan</b>"
    };
    $scope.obj = {};
    $scope.updateMessage = function(message, clear) {
        $timeout(function(){
            $scope.obj = $scope.obj || {};
            $scope.obj.message = $sce.trustAsHtml(message);
            if (message && clear) {
                $timeout(function(){
                    $scope.updateMessage(messages.nothing);
                }, 1000);
            }
        });
    }
    $scope.updateObj = function(key, val){
        $timeout(function(){
            $scope.obj[key] = val;
        });
    }

    $scope.pasteLink = function(){
        Apendo.pasteLink();
    }

    $scope.load = function() {
        Apendo.parentAcceptDrops({acceptDrops : false});
        LT17.unregisterAll();
        $scope.updateObj('loading', true);
        $scope.updateMessage(messages.sending);
        $('form textarea').blur();
        $timeout(function(){
            Apendo.loadPage($scope.obj);
        }, 500);
    }

    LT17.register('linkEntered', function(){
        $scope.updateMessage(messages.ready);
    });

    LT17.register('linkLeaved', function(){
        $scope.updateMessage(messages.nothing);
    });

    LT17.register('linkDropped', function(result){
        var token = result.accessToken;
        var rootUrl = result.rootUrl;
        if (!result.success || !token || !rootUrl) {
            $scope.updateObj('token', '');
            $scope.updateObj('valid', false);
            $scope.updateMessage(messages.failed, true);
            return;
        }
        if (token !== $scope.obj.token) {
            $scope.updateMessage(messages.dropped);
            $scope.updateObj('token', token);
            $scope.updateObj('rootUrl', rootUrl);
        }
    });

    LT17.register('clipboardHasValidUrl', function(){
        $timeout(function(){
            $scope.updateObj('valid', true);
        });
    });

    $scope.logout = function() {
        Apendo.userLogout({});
    }

    // we're accepting drops here
    logged = true;
    Apendo.parentAcceptDrops({acceptDrops : true});
    $scope.updateMessage(messages.nothing);
});

apendoCtrls.controller('NavBarCtrl', function($scope, $window){
    $scope.linksPublic = [
        { title : 'Tentang Apendo', href : '#about' },
        { title : 'Tambah User', href : '#register' }
    ];

    $scope.linksUser = [
          { title : 'Pengaturan', href : '#setting' },
          { title : 'Logout', href : '#', action : "logout"},
        ];

    $scope.linksAtSetting = [
          { title : 'Lelang', href : '#drop' },
          { title : 'Logout', href : '#', action : "logout"},
        ];

    $scope.linksAtAbout = [
          { title : 'Login', href : '#' },
          { title : 'Tambah User', href : '#register' }, // help and contacs will be here as well
        ];

    $scope.linksAtRegister = [
          { title : 'Tentang Apendo', href : '#about' },
          { title : 'Login', href : '#' }
        ];
	
	$scope.linksAtChecking = [
          { title : 'Info Lelang', href : '#checking' },
          { title : 'Logout', href : '#', action : "logout" }
        ];

    $window.updateNavBar = function(name) {
        $scope.links = $scope['links' + name];
        LT17.unregisterAll();
    }
});

apendoCtrls.controller('AboutCtrl', function($scope, $window){
    $window.updateNavBar('AtAbout');
    Apendo.parentAcceptDrops({acceptDrops : false});
});

apendoCtrls.controller('RegisterCtrl', function($scope, $window, $timeout, $location){
    $window.updateNavBar('AtRegister');
    $scope.obj = {};
    $scope.updateMessage = function(message, clear) {
        $timeout(function(){
            $scope.obj = $scope.obj || {};
            $scope.obj.message = message;
            if (message && clear) {
                $timeout(function(){
                    $scope.obj.error = false;
                    $scope.updateMessage('');
                }, 1000);
            }
        });
    }

    $scope.register = function() {
        var options = {};
        options.username = $scope.username;
        options.password = $scope.password;
        options.password2 = $scope.password2;
        LT17.register('userRegistered', function(result){
            LT17.unregister('userRegistered');
            if (result.success) {
                $scope.error = false;
                $scope.updateMessage('User "' + result.username + '" berhasil ditambahkan.', true);
                $timeout(function(){
                    $scope.updateMessage('');
                    $location.path('/');
                }, 1000);

                return;
            }
            $scope.obj.error = true;
            $scope.updateMessage('Terjadi kesalahan.', true);
        });
        $('form input').blur();
        $scope.updateMessage('Mencoba menambahkan user...');

        $timeout(function(){
            Apendo.userRegister(options);
        }, 500);
    }
    Apendo.parentAcceptDrops({acceptDrops : false});
});

apendoCtrls.controller('SettingCtrl', function($scope, $window, $timeout){
    $window.updateNavBar('AtSetting');
    /*$scope.setWorkspace = function(dir) {
        $timeout(function(){
            Apendo.userWorkspace = $scope.workspace = dir;
        });
    }

    $scope.changeWorkspace = function() {
			LT17.register('dirSelected', function(result){
				LT17.unregister('dirSelected');
				$scope.setWorkspace(result.dir);
				console.log("Default",result.dir);
			});
			Apendo.dirSelect({});
    } */

    // todo load from db
    $scope.currentProxy = 'Tidak menggunakan proxy.';

    $scope.setActive = function(name) {
        $scope.activeProxy = name;
        $('.proxy a').each(function(){
            $(this).removeClass('active');
        });
        $('#' + name).addClass('active');
    }

    $scope.setNoProxy = function() {
        if ($scope.activeProxy == 'noproxy')
            return;
        $scope.manualSettings = false;
        Apendo.setNoProxy();
        $scope.setActive('noproxy');
        $scope.currentProxy = 'Tidak menggunakan proxy.'
    }

    $scope.setManualProxy = function() {
        $scope.manualSettings = true;
        $scope.setActive('manual');
    }

    $scope.setManualProxyExec = function() {
        Apendo.setManualProxy(JSON.parse(angular.toJson($scope.conf) || '{}'));
        $scope.setActive('manual');
        $scope.manualSettings = false;
        $scope.currentProxy = 'Menggunakan proxy manual ' + $scope.conf.host + ':' + $scope.conf.port;
    }
    $scope.setAutoProxy = function() {
        if ($scope.activeProxy == 'auto')
            return;

        $scope.manualSettings = false;

        $scope.currentProxy = 'Mengecek proxy sistem, harap tunggu sebentar...';
        $scope.checking = true;
        LT17.register('systemProxyChecked', function(type){
            LT17.unregister('systemProxyChecked');
            $timeout(function(){
                if (type == 2) {
                    $scope.setActive('noproxy');
                    $scope.currentProxy = 'Tidak mengggunakan proxy.';
                } else {
                    $scope.currentProxy = 'Menggunakan proxy sistem.';
                    $scope.setActive('auto');
                }
                $scope.checking = false;
            });
        });

        $timeout(function(){
            Apendo.setAutoProxy();
        }, 250);
    }
    $scope.workspace = Apendo.userWorkspace;

    var proxyObj = {};
    try {
        proxyObj = JSON.parse(Apendo.proxyJson);
    } catch(ex) {
        proxyObj = {type: 'noproxy'};
    }

    $scope.setActive(proxyObj.type);

    if (proxyObj.type == 'manual') {
        // set the conf
        $scope.conf = $scope.conf || {};
        for (var k in proxyObj) {
            $scope.conf[k] = proxyObj[k];
        }
        $scope.currentProxy = 'Menggunakan proxy manual ' + $scope.conf.host + ':' + $scope.conf.port;

    } else if (proxyObj.type == 'auto') {
        $scope.currentProxy = 'Menggunakan proxy sistem.';
    }
    Apendo.parentAcceptDrops({acceptDrops : false});
});

/* apendoCtrls.controller('CheckingCtrl', function($scope, $window){
    $window.updateNavBar('AtChecking');
	var messages = {
        notice : "<b>Apakah anda akan melakukan lelang baru!!!.</b>"
    };
    $scope.newLelang = function() {
        Apendo.parentAcceptDrops({acceptDrops : false});
        LT17.unregisterAll();
        $scope.updateMessage(messages.notice);
        $timeout(function(){
            Apendo.loadPage($scope.obj);
        }, 500);
    }
}); */

apendoCtrls.config(function($routeProvider){
    $routeProvider
    .when('/', { templateUrl : "app/views/main.html", controller : "MainCtrl"});

    $routeProvider
    .when('/drop', { templateUrl : "app/views/drop.html", controller : "DropCtrl"});

    $routeProvider
    .when('/about', { templateUrl : "app/views/about.html", controller : "AboutCtrl"});

    $routeProvider
    .when('/register', { templateUrl : "app/views/register.html", controller : "RegisterCtrl"});

    $routeProvider
    .when('/setting', { templateUrl : "app/views/setting.html", controller : "SettingCtrl"});
});

var apendoApp = angular.module('apendoApp', ['ngRoute','apendoCtrls']);
