
var m = require('mithril');

// https://github.com/markdown-it/markdown-it
var markdown =  require('markdown-it')()
                  .use(require('markdown-it-footnote'));

var _dbs = require('./dbs');
// var _Header = require('./header');
// var _Footer = require('./footer');
var _Ui = require('./ui.js');

//     __    _       __
//    / /   (_)___  / /__
//   / /   / / __ \/ //_/
//  / /___/ / / / / ,<
// /_____/_/_/ /_/_/|_|
var _Link = {
  parent_id:null,
  tid:"",
  opened:false,
  oninit(vn){
    // console.log("INIT LINK : vn", vn);
    // define target id
    this.tid = vn.attrs.href;
  },
  onbeforeupdate(vn){
    this.tid = vn.attrs.href;
  },
  view(vn){
    // console.log(vn.attrs);

    this.tid_known =
      typeof vn.attrs.lang === 'undefined'
        ? false
        : typeof _dbs.data_byid[vn.attrs.lang][this.tid] === 'undefined'
          ? false
          : true;
    if (!this.tid_known) {
      // console.log(`!! in ${this.id}, target id ${this.tid} is unkonwn !!`);
    }
    if(this.opened && this.tid_known){
      console.log('link vn.state', vn.state);
      // traget object

      this.tob = Object.assign({"nested":true},_dbs.data_byid[vn.attrs.lang][this.tid]);
      // this.tob = Object.assign({'lang':vn.attrs.lang}, this.tob);
      console.log('this.tob',this.tob);

      return m('div', {'class':'opened-link'},
          [
            m('span', {'class':"link text"}, vn.children),
            m('div', {
              'class':'close-link-btn',
              onclick(e){
                // e.preventDefault();
                console.log('click close btn', this);
                vn.state.opened = false;
                // return false;
              }
            }),//, m('span', m.trust("&#128473;"))),
            typeof this.tob.childs !== "undefined"
              ? m(_Enonce, this.tob)
              : m(_Item, this.tob)
          ]
        );
    }else{
      // console.log(vn);
      return m('a', {
          'class':'link',
          'href':'#'+this.tid,
          'rel':this.tid,
          onclick(e){
            e.preventDefault();
            console.log('click', this);
            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 (n.tag == 'img') {
        // record the href attribute for cross reference
        n.attrs = {
          'src':nodes[i].attributes.src.value,
          'alt':nodes[i].attributes.alt.value
        };
      }
      if(nodes[i].childNodes.length){
        // again parse node's childs
        n.childs = parseTextDom(nodes[i].childNodes);
      }
    }else if (nodes[i].textContent.length > 0){
      // 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){
  // console.log('populateTextDom : '+i,n);
  return n.tag == "#text"
    ? m.trust(n.text)
    : m(
        n.tag != 'a' ? n.tag : _Link,
        typeof n.attrs != "undefined" ? Object.assign({"lang":this.attrs.lang},n.attrs) : {},
        typeof n.childs != "undefined"
          ? n.childs.map(populateTextDom, this)
          : typeof n.text != "undefined"
            ? m.trust(n.text)
            : null
      );
}

var _Text = {
  id:null,
  text:"",
  texthtml:"",
  textdom:null,
  textchilds:[],
  parsetext(vn){
    // if(vn.attrs.nested){debugger;}
    // console.log('parsetext', this);
    // !! we need to convert markdown to html here because parseTextDom() is recursive through nodes tree
    // convert markdown to html
    // if(typeof this.text === "undefined"){
    //   debugger;
    // }
    this.texthtml = markdown.render(this.text);
    // convert html string to virtual dom
    this.textdom = new DOMParser().parseFromString(this.texthtml, "text/html");
    // get the text nodes (avoid html document extra) and apply some transformations
    this.textchilds = parseTextDom(this.textdom.getElementsByTagName('body')[0].childNodes);
  },
  oninit(vn){
    // if(vn.attrs.nested){debugger;}
    this.id = vn.attrs.id;
    this.text = vn.attrs.text || "";
    // if(vn.attrs.nested){debugger;}
    this.parsetext(vn);
  },
  onbeforeupdate(vn,old){
    // if(vn.attrs.nested){debugger;}
    this.text = vn.attrs.text;
    this.parsetext(vn);
  },
  view(vn){
    // console.log('_Text :: view : '+vn.attrs.slug, vn);
    return m('div',
      {'class':'text'},
      // loop through childNodes list generated by parseTextDom() in init
      // TODO : pass lang to populateTextDom
      this.textchilds.map(populateTextDom, vn)
    ); // /m.div.text
  } // view:
}

//     ______
//    /  _/ /____  ____ ___
//    / // __/ _ \/ __ `__ \
//  _/ // /_/  __/ / / / / /
// /___/\__/\___/_/ /_/ /_/
var _Item = {
  id:null,
  part:null,
  type:null,
  nested:false,
  oninit(vn){
    // if(vn.attrs.nested){debugger;}
    // TODO: what to do with items without text ? as type title for example
    // if(typeof vn.attrs.text === 'undefined'){debugger;}
    // console.log('vn.attrs', vn.attrs);
    this.id = vn.attrs.id;
    this.type = vn.attrs.type;
    // vn.state.part = vn.state.slug.match(/^(\d)(.+)/)[1];
    this.text = vn.attrs.text;
    this.nested = vn.attrs.nested || false;
    this.dottype = vn.attrs.dottype || null;
  },
  onbeforeupdate(vn, old){
    this.nested = vn.attrs.nested || false;
    this.type = vn.attrs.type;
    this.text = vn.attrs.text;
  },
  view(vn){
    // if(this.id == "340c2"){
    //   console.log(`${this.id} vn.attrs `,vn.attrs);
    // }
    return m("section", {
        'id':this.id,
        // 'class':'item'+(this.nested ? ' nested':'')
        'class' :`item${this.nested ? ' nested':''} ${this.dottype}`
      },
      // filter by type if active filter
      !_dbs.active_type_filter || _dbs.active_type_filter == vn.attrs.dottype || vn.attrs.nested
        ? [
            // create title node (only if not nested)
            !this.nested
              ? m("h3", {
                  // 'ref':vn.attrs.href,
                  // onclick(e){ WHAT IS THIS STATE ACTIVE ???
                  //   vn.state.active = vn.state.active ? 0 : 1;
                  // }
                }, m.trust(markdown.renderInline(this.type)))
              : null,
            // create text node
            typeof vn.attrs.text !== "undefined"
              ? m(_Text, {'text':this.text, 'id':this.id, 'lang':vn.attrs.lang})
              : null,
            // add children (only if not nested)
            // typeof vn.attrs.childs !== 'undefined' && !this.nested
            //   ? vn.attrs.childs.map(c => { return m(_Item, c); })
            //   : null
          ]
        :null
    )
  }
};

//     ______
//    / ____/___  ____  ____  ________
//   / __/ / __ \/ __ \/ __ \/ ___/ _ \
//  / /___/ / / / /_/ / / / / /__/  __/
// /_____/_/ /_/\____/_/ /_/\___/\___/
var _Enonce = {
  partid:null,
  // id:null,
  title:null,
  // text:null,
  // nested:false,
  // childs:[],
  oninit(vn){
    // if(vn.attrs.nested){debugger;}
  //   // console.log('Enonce on init', vn);
    this.partid = vn.attrs.partid;
    // this.id = vn.attrs.id;
    this.title = vn.attrs.title || "";
    // this.text = vn.attrs.text;
    // this.childs = vn.attrs.childs || [];
    // this.nested = vn.attrs.nested || false;
    this.dottype = vn.attrs.dottype || "no-dottype";
  },
  onbeforeupdate(vn, old) {
    // console.log(vn.attrs.childs);
    this.title = vn.attrs.title || "";
    // this.text = vn.attrs.text;
    // this.childs = vn.attrs.childs || [];
    // this.nested = vn.attrs.nested || false;
    // if(vn.attrs.id == '1d1') console.log('_Enonce UPDATE, text :', vn.attrs.text);
  },
  view(vn){
    // if(vn.attrs.nested){
    //   console.log('ennonce vn.attrs', vn.attrs);
    // }
    return m("section", {
      'id'    :vn.attrs.id,
      'class' :`enonce${vn.attrs.nested ? ' nested':''} ${this.dottype}`
    },
    [
      // filter by type if active filter (but let map on children)
      !_dbs.active_type_filter || _dbs.active_type_filter == vn.attrs.dottype
        // create title node (only if not nested)
        ? !vn.attrs.nested ? m("h2", {}, m.trust(markdown.renderInline(this.title))) : null
        : null,
      !_dbs.active_type_filter || _dbs.active_type_filter == vn.attrs.dottype || vn.attrs.nested
        // create text node
        ? m(_Text, {'text':vn.attrs.text, 'id':vn.attrs.id, 'nested':vn.attrs.nested})
        : null,
      // add children (only if not nested)
      typeof vn.attrs.childs !== 'undefined' && !vn.attrs.nested
        ? vn.attrs.childs.map(c => {
          c.lang = vn.attrs.lang;
          return m(_Item, c);
        })
        : null
    ])
  }
}

//     ____             __
//    / __ \____ ______/ /_
//   / /_/ / __ `/ ___/ __/
//  / ____/ /_/ / /  / /_
// /_/    \__,_/_/   \__/
var _Part = {
  oninit(vn){
    // this.id = vn.attrs.id;
    // this.title = vn.attrs.title || '';
    // this.enonces = vn.attrs.enonces;
  },
  onbeforeupdate(vn, old){
    // console.log('_Part, onbeforeupdate old',old);
    // this.title = vn.attrs.title || '';
    // this.enonces = vn.attrs.enonces;
  },
  view(vn){
    // console.log("part enonces", vn.attrs.enonces);
    return m("section", {
        'id'    :vn.attrs.id,
        'class' :'part'
      },
      [
        // create title node
        m("h1", {'class':'part-title', 'part':vn.attrs.id}, m.trust(markdown.renderInline(vn.attrs.title))),
        // create text node
        vn.attrs.enonces.map(e => {
          // console.log(e.title +" - "+ e.type);
          // var title = e.title || '';
          switch (e.type) {
            case "title":
              // handle titles
              // console.log('title');
              return !_dbs.active_type_filter
                ? m("h2", {'class':'title'}, m.trust(markdown.renderInline(e.title)))
                : null ;
              break;
            case "filet":
              // handle filets
              // console.log('filet');
              return m("h4", {'class':'filet'}, m.trust(markdown.renderInline(e.title)));
              break;
            default:
              // or build structure
              e.lang = vn.attrs.lang;
              return m(_Enonce, Object.assign({"partid":vn.attrs.id},e));
          }
        })
      ]
    )
  }
}

//     ____      __
//    /  _/___  / /__________
//    / // __ \/ __/ ___/ __ \
//  _/ // / / / /_/ /  / /_/ /
// /___/_/ /_/\__/_/   \____/
var _Intro = {
  oninit(vn){
    // console.log('_Intro : oninit : vn', vn);
    this.id = vn.attrs.id;
    this.text = vn.attrs.text || '';
  },
  onbeforeupdate(vn, old){
    this.id = vn.attrs.id;
    this.text = vn.attrs.text || '';
  },
  view(vn){
    return m("section", {'class':'intro'}, m("p",m.trust(markdown.renderInline(this.text))));
  }
}

//   ______          __
//  /_  __/__  _  __/ /_
//   / / / _ \| |/_/ __/
//  / / /  __/>  </ /_
// /_/  \___/_/|_|\__/
module.exports = {
  // oninit(vn){
  //   // this.lang = vn.attrs.lang;
  //   console.log('ModeText oninit : lang', vn.attrs.lang);
  //   // i18next.changeLanguage(vn.attrs.lang);
  // },
  oncreate(vn){
    document.body.classList.add('mode-text');
    _Ui.init();
  },
  // onbeforeupdate(vn, old){
  //   console.log('ModeText onbeforeupdate : lang', vn.attrs.lang);
  //   // i18next.changeLanguage(vn.attrs.lang);
  // },
  view(vn){
    // console.log('_ModeText view', vn.attrs.lang);
    console.log('_dbs.active_type_filter : ', _dbs.active_type_filter);
    return m('main', {id:"content", 'class':'mode-text'}, _dbs.data[vn.attrs.lang].map((p) => {
        // console.log("MAP _dbs", p);
        p.lang = vn.attrs.lang;
        if(p.id == 'intro'){
          return m(_Intro,p);
        }else{
          return m(_Part,p);
        }
      })
    );
  }

}
