/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  // Sets app default base URL
  app.baseUrl = '/';
  if (window.location.port === '') { // if production
    // Uncomment app.baseURL below and
    // set app.baseURL to '/your-pathname/' if running from folder in production
    // app.baseUrl = '/polymer-starter-kit/';
  }

  app.displayInstalledToast = function() {
    // Check to make sure caching is actually enabled—it won't be in the dev environment.
    if (!Polymer.dom(document).querySelector('platinum-sw-cache').disabled) {
      Polymer.dom(document).querySelector('#caching-complete').show();
    }
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {
    console.log('Our app is ready to rock!');
  });

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  // Main area's paper-scroll-header-panel custom condensing transformation of
  // the appName in the middle-container and the bottom title in the bottom-container.
  // The appName is moved to top and shrunk on condensing. The bottom sub title
  // is shrunk to nothing on condensing.
  window.addEventListener('paper-header-transform', function(e) {
    var appName = Polymer.dom(document).querySelector('#mainToolbar .app-name');
    var middleContainer = Polymer.dom(document).querySelector('#mainToolbar .middle-container');
    var bottomContainer = Polymer.dom(document).querySelector('#mainToolbar .bottom-container');
    var detail = e.detail;
    var heightDiff = detail.height - detail.condensedHeight;
    var yRatio = Math.min(1, detail.y / heightDiff);
    // appName max size when condensed. The smaller the number the smaller the condensed size.
    var maxMiddleScale = 0.50;
    var auxHeight = heightDiff - detail.y;
    var auxScale = heightDiff / (1 - maxMiddleScale);
    var scaleMiddle = Math.max(maxMiddleScale, auxHeight / auxScale + maxMiddleScale);
    var scaleBottom = 1 - yRatio;

    // Move/translate middleContainer
    if (middleContainer) {
      Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);
    }

    // Scale bottomContainer and bottom sub title to nothing and back
    if (bottomContainer) {
      Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);
    }

    // Scale middleContainer appName
    Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
  });

  // Scroll page to top and expand header
  app.scrollPageToTop = function() {
    app.$.headerPanelMain.scrollToTop(true);
  };

  app.closeDrawer = function() {
    app.$.paperDrawerPanel.closeDrawer();
  };


  //--------------------//
  //-- Customizations --//
  //--------------------//
  app.navigator = [];

  app.navigatorList = [];

  app.hideBackButton = true;

  app.hideMenuButton = !app.hideBackButton;

  app.title = '';

  app.configuracaoOk = false;

  app.loginOk = false;

  app.tituloPrincipal = 'P@stor';

  app.menuSelecionado = function(e) {
    var pagina = e.detail.item.getAttribute('data-route');
    //a partir do menu selecionado, procura a respectiva fila de navegação 
    var queue = null;
    app.navigatorList.forEach(function(item) {
      if (item.route === pagina) {
        queue = item;
      }
    }, this);
    //se não encontrar, cria uma entrada nova na estrutura queueList para referenciar o item de menu
    if (queue === null) {
      queue = {
        route: pagina,
        navigator: []
      };
      queue.navigator.push({
        titulo: app.tituloPrincipal
      });
      app.navigatorList.push(queue);
    }
    app.navigator = queue.navigator;
    //altera titulo principal
    app.carregaTituloDaPagina(pagina);
    //efeito no ícone do menu
    var icon = document.querySelector('a[data-route=' + pagina + '] > iron-icon');
    if (icon) {
      if (icon.classList.contains('rotate-1')) {
        icon.classList.remove('rotate-1');
        icon.classList.add('rotate-2');
      } else {
        icon.classList.remove('rotate-2');
        icon.classList.add('rotate-1');
      }
    }
    if ( pagina === 'estatistica' ) {
      document.querySelector('pastor-estatistica')._redesenhar();
    }   
  };

  app.carregaTitulo = function(titulo) {
    var pastorTitulo = document.querySelector("pastor-titulo");
    if (pastorTitulo.title != titulo) {
      pastorTitulo.animate(titulo);
      app.navigator[app.navigator.length - 1].titulo = titulo;
    }
  };

  app.carregaTituloDaPagina = function(pagina) {
    if (app.navigator.length === 1) {
      app.hideBackButton = true;
      //recupera o título do menu selecionado
      var span = document.querySelector('a[data-route=' + pagina + '] > span');
      var title = null;
      if (span !== null) {
        var text = span.getAttribute('data-titulo');
        if (text === null || text.trim().length === 0) {
          title = span.innerText;
        } else {
          title = text;
        }
      }
      app.carregaTitulo(title);
    } else {
      app.hideBackButton = false;
      //recupera o título do último menu de navegação
      app.carregaTitulo(app.navigator[app.navigator.length - 1].titulo);
    }
  };

  app.addVoltar = function(callback, target) {
    if (callback) {
      if (target) {
        callback = callback.bind(target);
      }
      var pTitle = document.querySelector('pastor-titulo');
      var nav = {
        callback: callback,
        titulo: pTitle.title
      };
      app.hideBackButton = false;
      app.navigator.push(nav);
    }
  };

  app.voltar = function() {
    if (app.navigator.length > 1) {
      app.navigator[app.navigator.length - 1].callback();
      app.navigator.pop();
      if (app.navigator.length === 1) {
        app.hideBackButton = true;
      }
      app.carregaTitulo(app.navigator[app.navigator.length - 1].titulo);
    }
  };

  app.configuracaoCompleta = function(config) {
    app.configuracaoOk = true;
    this.route = 'login';
    var login = document.querySelector('pastor-login');
    login.load();
  };

  app.configuracaoIncompleta = function() {
    app.configuracaoOk = false;
    app.loginOk = false;
    app.route = 'config';
  };

  app.iniciandoConfiguracao = function() {
    app.route = 'config';
  };

  app.usuarioLogou = function() {
    var config = document.querySelector('pastor-config');
    if (config.isPerfilGrupo() || config.isPerfilMinisterio() || config.isPerfilCelula()) {
      var grupo = config.grupo;
      var ref = new Firebase(getFirebaseUrl() + '/' + getContextoCompleto());
      ref.once('value', function ok(snapshot) {
        var objGrupo = snapshot.val();
        app.tituloPrincipal = objGrupo.nome;
        document.querySelector('pastor-pessoas').load(config.contexto, true);
        document.querySelector('pastor-grupos-cadastro').load(config.contexto);
        document.querySelector('pastor-frequencia').load(config.contexto);
        app.loginOk = true;
        app.carregaTitulo(app.tituloPrincipal);
        app.route = 'pessoas';
        config.valida();
      }, function erro(e) {
        app.loginOk = false;
        if (isPermissionDenied(e)) {
          app.configuracaoOk = false;
          ref.unauth();
          app.route = 'config';
          var config = document.querySelector('pastor-config');
          config.alerta('O usuário não possui permissão para acessar o contexto');
        }
      }, this);
    }
  };

  app.loginInvalido = function() {
    app.loginOk = false;
    app.route = 'login';
  };

  app.frequenciaAtualizada = function() {
    document.querySelector('pastor-pessoas').reload();
    document.querySelector('pastor-estatistica').load();
  };

})(document);
