/**
 * @Author: Bachir Soussi Chiadmi <bach>
 * @Date:   16-04-2017
 * @Email:  bachir@figureslibres.io
 * @Last modified by:   bach
 * @Last modified time: 18-04-2017
 * @License: GPL-V3
 */

require('normalize.css/normalize.css');
require('./fonts/amiri/amiri.css');
require('./fonts/dejavu/dejavu.css');
require('./fonts/opensans/opensans.css');

var m = require('mithril');
// var marked = require('marked');
var markdown =  require('markdown-it')()
                  .use(require('markdown-it-footnote'));

// console.log("Hello Ethica");

var _db = require('./jsondb/2-Appuhn-FR-ethicadb.json')
// console.log("_db", _db);

var _db_by_id = {};
for (p in _db) {
  for (e in _db[p]) {
    // console.log(_db[p][e]);
    _db_by_id[_db[p][e].id] = _db[p][e];
    for (c in _db[p][e]){
      // console.log(_db[p][e][c]);
      _db_by_id[_db[p][e][c].id] = _db[p][e][c];
    }
  }
}
console.log('_db_by_id', _db_by_id);

//     __    _       __
//    / /   (_)___  / /__
//   / /   / / __ \/ //_/
//  / /___/ / / / / ,<
// /_____/_/_/ /_/_/|_|
var _Link = {
  targetid:"",
  opened:false,
  oninit: function(vn){
    // console.log("INIT LINK : vn", vn);
    // define target id
    vn.state.tid = vn.attrs.href;
  },
  view: function(vn){
    if(vn.state.opened){
      // console.log('vn.state.tid', vn.state);
      return m('div', {'class':'opened-link'},
          [
            m('span', {'class':"link text"}, vn.children),
            typeof _db_by_id[vn.state.tid].childs != "undefined"
              ? m(_Enonce, _db_by_id[vn.state.tid])
              : m(_Item, _db_by_id[vn.state.tid])
          ]
        );
    }else{
      // console.log(vn);
      return m('a', {
          'class':'link',
          'href':'#'+vn.state.tid,
          'rel':vn.state.tid,
          onclick:function(e){
            e.preventDefault();
            console.log('click', vn);
            vn.state.opened = true;
            return false;
          }
        }, vn.children);
    }

  }
}

//   ______          __
//  /_  __/__  _  __/ /_
//   / / / _ \| |/_/ __/
//  / / /  __/>  </ /_
// /_/  \___/_/|_|\__/

// recusive function to record information of all subnodes
function parseTextDom(nodes){
  var list = [];
  // loop through childNodes
  for (var i = 0; i < nodes.length; i++) {
    var n = {};
    if(typeof nodes[i].localName != "undefined"){
      n.tag=nodes[i].localName;
      if (n.tag == 'p') {
        // replace p by div as we will insert other div in them
        n.tag = 'div';
        n.attrs = {'class':'paragraph'};
      }
      if (n.tag == 'a') {
        // record the href attribute for cross reference
        n.attrs = {'href':nodes[i].attributes.href.value};
      }
      if(nodes[i].childNodes.length){
        // again parse node's childs
        n.childs = parseTextDom(nodes[i].childNodes);
      }
    }else if (nodes[i].textContent.length > 1){
      // if node has no localName it is probably a #text node
      // we record it if it's not empty
      n.tag='#text';
      n.text=nodes[i].textContent;
    }
    // add the node to the list if it has a tag
    if(typeof n.tag != "undefined")
      list.push(n);
  }
  return list;
}

// recusive fucntion to generate mithril object from information recorded with parseTextDom()
function populateTextDom(n,i){
  // console.log('populateTextDom : '+i,n);
  return n.tag == "#text"
    ? m.trust(n.text)
    : m(
        n.tag != 'a' ? n.tag : _Link,
        typeof n.attrs != "undefined" ? n.attrs : {},
        typeof n.childs != "undefined"
          ? n.childs.map(populateTextDom)
          : typeof n.text != "undefined"
            ? m.trust(n.text)
            : null
      );
}

var _Text = {
  textchilds:[],
  oninit: function(vn){
    debug = vn.attrs.id == '1a5';
    // convert markdown to html
    var texthtml = markdown.render(vn.attrs.text)
    // parse html string to virtual dom
    var textdom = new DOMParser().parseFromString(texthtml, "text/html");
    // get the text nodes (avoid html document extra)
    if(debug) console.log('textdom',textdom);
    vn.state.textchilds = parseTextDom(textdom.getElementsByTagName('body')[0].childNodes);
  },
  view: function(vn){
    // console.log('_Text :: view : '+vn.attrs.slug, vn);
    // console.log('vn.state.textchilds', vn.state.textchilds);
    return m('div',
      {'class':'text'},
      // loop through childNodes list generated by parseTextDom() in init
      vn.state.textchilds.map(populateTextDom)
    ); // /m.div.text
  } // view:
}

//     ______
//    /  _/ /____  ____ ___
//    / // __/ _ \/ __ `__ \
//  _/ // /_/  __/ / / / / /
// /___/\__/\___/_/ /_/ /_/
var _Item = {
  id:null,
  part:null,
  type:null,
  nested:false,
  oninit: function(vn){
    // console.log('vn.attrs', vn.attrs);
    vn.state.id = vn.attrs.id;
    // vn.state.part = vn.state.slug.match(/^(\d)(.+)/)[1];
    vn.state.nested = vn.attrs.nested | false;
  },
  view: function(vn){
    return m("section", {
        'id':vn.state.id,
        'class':'item'+(vn.state.nested ? ' nested':'')
      },
      [
        // create title node
        m("h3", {
            // 'ref':vn.attrs.href,
            onclick: function(e){
              vn.state.active = vn.state.active ? 0 : 1;
            }
          }, vn.attrs.type),
        // create text node
        m(_Text, {'text':vn.attrs.text, 'id':vn.attrs.id})
      ]
    )
  }
};

//     ______
//    / ____/___  ____  ____  ________
//   / __/ / __ \/ __ \/ __ \/ ___/ _ \
//  / /___/ / / / /_/ / / / / /__/  __/
// /_____/_/ /_/\____/_/ /_/\___/\___/
var _Enonce = {
  partid:null,
  id:null,
  title:null,
  nested:false,
  childs:[],
  oninit:function(vn){
    // console.log('Enonce on init', vn);
    vn.state.partid = vn.attrs.partid;
    vn.state.id = vn.attrs.id;
    vn.state.title = vn.attrs.title;
    vn.state.childs = vn.attrs.childs;
    vn.state.nested = vn.attrs.nested | false;
  },
  view: function(vn){
    return m("section", {
      'id'    :vn.state.id,
      'class' :'enonce'+(vn.state.nested ? ' nested':'')
    },
    [
      // create title node
      m("h2", {}, vn.attrs.title),
      // create text node
      m(_Text, {'text':vn.attrs.text, 'id':vn.state.id}),
      // addd children
      vn.state.childs.map(function(c){
        return m(_Item, c)
      })
    ])
  }
}

//     ____             __
//    / __ \____ ______/ /_
//   / /_/ / __ `/ ___/ __/
//  / ____/ /_/ / /  / /_
// /_/    \__,_/_/   \__/
var _Part = {
  id:null, // get the part number
  title:null,
  enonces:[],
  oninit:function(vn){
    // console.log('Part on init', vn);
    vn.state.id = vn.attrs.id;
    vn.state.title = vn.attrs.title;
    vn.state.enonces = vn.attrs.enonces;
  },
  view: function(vn){
    return m("section", {
      'id'    :vn.state.id,
      'class' :'part'
    },
    [
      // create title node
      m("h1", {'class':'part'}, vn.state.title),
      // create text node
      vn.state.enonces.map(function(e){
        return m(_Enonce, Object.assign({"partid":vn.state.id},e))
      })
    ])
  }
}

//   ______
//  /_  __/_______  ___
//   / / / ___/ _ \/ _ \
//  / / / /  /  __/  __/
// /_/ /_/   \___/\___/
var _Tree = {
  view: function(){
    // return m('main', {id:"content"}, DataItems.map(c => m(_Item,c)));
    return m('main', {id:"content"}, _db.map(function(p){
        // console.log("MAP _db", _db[k]);
        return m(_Part,p);
      })
    );
  }
}
m.mount(document.getElementById('app'), _Tree);
