'use strict';

var pathModule = require('path');
var _ = require('lodash');
var url = require('url');

hexo.extend.helper.register('generate_nav', function(){
  var type = this.page.canonical_path.split('/')[0];
  var sidebar = this.site.data.sidebar[type];
  var path = pathModule.basename(this.path);
  var list = {};
  var prefix = 'sidebar.' + type + '.';

  for (var i in sidebar){
    for (var j in sidebar[i]){
      list[sidebar[i][j]] = j;
    }
  }

  var keys = Object.keys(list);
  var index = keys.indexOf(path);
  var html = '';

  if (index > 0){
    html += '<a href="' + keys[index - 1] + '" class="page-nav page-prev pull-left" title="' + this.__(prefix + list[keys[index - 1]]) + '">' +
      '<i class="pe-7s-angle-left"></i><span>' + this.__('page.prev') + '</span></a>';
  }

  if (index < keys.length - 1){
    html += '<a href="' + keys[index + 1] + '" class="page-nav page-next pull-right" title="' + this.__(prefix + list[keys[index + 1]]) + '">' +
      '<span>' + this.__('page.next') + '</span><i class="pe-7s-angle-right"></i></a>';
  }

  return html;
});

hexo.extend.helper.register('generate_menu', function() {
  var self = this;
  var prefix = 'menu.';
  var html = '';

  if (typeof self.theme.menu !== 'undefined') {
    _.each(self.theme.menu, function(menu, title) {
      html += '<a class="btn btn-material btn-' + menu.theme + '" href="' + menu.link + '" target="_blank">' + self.__(prefix + title) + '</a>';
    });
  }

  return html;
});

hexo.extend.helper.register('generate_sidebar', function(className) {
  var self = this;
  var type = self.page.canonical_path.split('/')[0];
  var sidebar = self.site.data.sidebar[type];
  var path = pathModule.basename(self.path);
  var html = '';
  var prefix = 'sidebar.' + type + '.';

  _.each(sidebar, function(menu, title) {
    html += '<strong class="' + className + '-title">' + self.__(prefix + title) + '</strong>';

    _.each(menu, function(link, text) {
      var itemClass = className;
      if (link === path) itemClass += ' active';

      html += '<a href="' + link + '" class="' + itemClass + '">' + self.__(prefix + text) + '</a>';
    })
  });

  return html;
});

hexo.extend.helper.register('get_lang', function(lang){
  var self = this;
  return self.site.data.languages[lang]? lang : '';
});
