/* global API, asyncStorage, ErrorManager, debug, SecurityController, UIManager, Utils */
/* jshint maxstatements:50 */
'use strict';

var SecurityUI = new function () {

    function clearNode(node) {
        while (node.firstChild) {
            node.removeChild(node.firstChild);
        }
    }

    function checkOtherSessionsVisibility() {
        var otherSessionsContainer = document.querySelector('#sessions-container-other');
        var numberOfOtherSessions = otherSessionsContainer.querySelectorAll('.session').length;

        if (numberOfOtherSessions === 0) {
            otherSessionsContainer.classList.add('hide');
        }
        else {
            otherSessionsContainer.classList.remove('hide');
        }
    }

    function removeSession(currentTemplate) {
        var sessionIdOfClickedSession = currentTemplate.getAttribute('data-sessionid');
        SecurityController.closeSingleSession(sessionIdOfClickedSession, function () {
            currentTemplate.parentNode.removeChild(currentTemplate);
            checkOtherSessionsVisibility();
        });
    }
    
    function removeAllSessions(){
        SecurityController.closeAllSessions(function(){
            clearNode(document.querySelector('#sessions-container-other-list'));
            checkOtherSessionsVisibility();
        });
    }
    
    function findSessionTemplate(sessionId){
        var allSessions = document.querySelectorAll('#sessions-container-other-list .session');
        var numberOfSessions = allSessions.length;
        for (var i = 0; i < numberOfSessions ; i++){
            var currentSession = allSessions[i];
            if(currentSession.getAttribute('data-sessionid') === sessionId){
                return currentSession;
            }
        }
    }

    function fillSessionTemplate(template, session) {
        var _ = navigator.mozL10n.get;

        template.querySelector('.platform').textContent = session.platform;
        template.querySelector('.device').textContent = session.device;

        var date = Utils.parseSpanishFormat(session.lastUsed);
        template.querySelector('.last-used').textContent = _('security-last-used') + ': ' + Utils.utcDateToWords(date);

        if (session.device === '') {
            template.classList.add('no-platform');
        }

        if (template.classList.contains('current')) {
            template.querySelector('.last-used').textContent = _('security-currently-active');
        }
        
        var humanName = session.device ? session.device : session.platform;
        template.setAttribute('data-session-human-name', humanName);
    }

    function init(dom) {
        this.dom = dom;

        dom.backFromSecurity.addEventListener('click', function () {
            UIManager.load('main');
        });

        dom.changePasswordContainer.addEventListener('click', function () {
            UIManager.loadPageOnBrowser(Config.environment.resetURL + "?hideCloseButton=true");
        });
        
        dom.closeSingleSessionConfirmationButton.addEventListener('click', function(e){
            var sessionId = UIManager.getParentOfClass(e.target, 'modalDialog').getAttribute('data-sessionid');
            var sessionTemplate = findSessionTemplate(sessionId);
            removeSession(sessionTemplate);
        });
        
        dom.closeAllSessionsConfirmationButton.addEventListener('click', function(e){
            removeAllSessions();
        });
    }

    function getClearSessionTemplate() {
        return document.querySelector('#session-template-container > div.session').cloneNode(true);
    }

    function listSessions(callback) {
        SecurityController.listSessions(function (currentSession, otherSessions) {
            var currentSessionTemplate = getClearSessionTemplate();
            currentSessionTemplate.classList.add('current');
            fillSessionTemplate(currentSessionTemplate, currentSession);


            var currentSessionContainer = document.querySelector('#sessions-container-current');
            var otherSessionsList = document.querySelector('#sessions-container-other-list');

            clearNode(currentSessionContainer);
            clearNode(otherSessionsList);

            currentSessionContainer.appendChild(currentSessionTemplate);

            var sessionKeys = Object.keys(otherSessions);
            var numberOfSessions = sessionKeys.length;
            for (var i = 0; i < numberOfSessions; i++) {
                var sessionId = sessionKeys[i];
                var template = getClearSessionTemplate();
                template.setAttribute('data-sessionid', sessionId);
                fillSessionTemplate(template, otherSessions[sessionId]);

                template.querySelector('i').addEventListener('click', function (e) {
                    var session = this.parentNode;
                    var messageDom = document.querySelector('#close-single-session-openModal .content > p');
                    var modal = document.querySelector('#close-single-session-openModal');
                    
                    modal.setAttribute('data-sessionid', session.getAttribute('data-sessionid'));
                    
                    navigator.mozL10n.localize(
                            messageDom, // Element
                            'security-close-one-confirmation', // l10n Key
                            {
                                device: session.getAttribute('data-session-human-name')// Params
                            });
                            
                     
                    window.location = '#close-single-session-openModal';
                });
                otherSessionsList.appendChild(template);
            }

            checkOtherSessionsVisibility();
            callback();
        });
    }


    return {
        init: init,
        listSessions: listSessions
    };
};