document.write('<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js" async defer></script>');

function getLocation(href) {
  var l = document.createElement('a');
  l.href = href;
  return l;
};

function getParamFromUrl(url) {
  var regex = /[?&]([^=#]+)=([^&#]*)/g;
  var params = {};
  var match = [];
  match = regex.exec(url);
  while (match) {
    params[match[1]] = match[2];
    match = regex.exec(url);
  }
  return params;
}

function buidHTML(name, table, opt) {
  opt = opt || {};
  var defUI = {
    title: {
      backgroundColor: '#F44336',
      color: '#FFFFFF'
    },
    headline: {
      backgroundColor: '#74A23C',
      color: '#FFFFFF',
    },
    header: {
      backgroundColor: '#950F0F',
      color: '#FFFFFF',
    },
    oddRow: {
      backgroundColor: '#FFFFFF',
      color: '#000000',
    },
    oddRowWin: {
      backgroundColor: '#CC4747',
      color: '#FFFFFF',
    },
    evenRow: {
      backgroundColor: '#F2F2F2',
      color: '#000000',
    },
    evenRowWin: {
      backgroundColor: '#CA5D5D',
      color: '#FFFFFF',
    },
  };
  var ui = Object.assign({}, defUI, table.ui);

  var buildHeaderEle = function(title) {
    return '\
      <th style="background-color:' + ui.header.backgroundColor + '; color:' + ui.header.color + '">' + title + '</th>\
    ';
  };

  var buildHeader = function() {
    var arr = new Array(table.nCols || table.header.length);
    var ele = [];
    for (var i = 0; i < arr.length; i++) {
      ele.push(buildHeaderEle(table.header[i]));
    }
    return ele.join('');
  };

  var buildTdEle = function(ri, ci, ele) {
    return '\
      <td style="' + jsonToStyle(tdStyle(ri, ci)) + '"><span>' + parse(ele) + '</span></td>\
    ';
  };

  var buildTd = function(ri, line) {
    var arr = new Array(table.nCols || table.header.length);
    var ele = [];
    for (var ci = 0; ci < arr.length; ci++) {
      ele.push(buildTdEle(ri, ci, line[ci]));
    }
    return ele.join('');
  };

  var buildTrEle = function(ri, line) {
    return '\
      <tr style="' + jsonToStyle(trStyle(ri)) + '" class="' + (opt.isWinRow[ri] ? 'win' : '') + '">' + buildTd(ri, line) + '</tr>\
    ';
  };

  var buildTr = function() {
    var ele = [];
    for (var ri = 0; ri < table.data.length; ri++) {
      var line = table.data[ri];
      ele.push(buildTrEle(ri, line));
    }
    return ele.join('');
  };

  var jsonToStyle = function(obj) {
    var mapping = {
      'backgroundColor': 'background-color',
    };
    var re = [];
    for (var k in obj) {
      re.push((mapping[k] || k) + ':' + obj[k]);
    }
    return re.join(';');
  };

  var trStyle = function(ri) {
    let isWin = opt.isWinRow[ri];
    if ((ri - 1) % 2 === 0) {
      return isWin ? ui.evenRowWin : ui.evenRow;
    } else {
      return isWin ? ui.oddRowWin : ui.oddRow;
    }
  };

  var tdStyle = function(ri, ci) {
    let style = {};
    if (table.colHighlight && table.colHighlight[ci] && opt.isWinRow[ri]) {
      style.backgroundColor = table.colHighlight[ci];
    }
    if (table.colTextHighlight && table.colTextHighlight[ci] && opt.isWinRow[ri]) {
      style.color = table.colTextHighlight[ci];
    }
    return style;
  };

  var parse = function(item) {
    if (item === '__WIN__') {
      return 'TRÚNG';
    } else if (item === '__LOST__') {
      return 'XỊT';
    }
    if (item.indexOf('[[') >= 0) {
      let icon = item.replace(/\[\[(.*)\]\]/g, '<i class="fa fa-$1"></i>');
      if (item.indexOf('[[circle-o-notch]]') >= 0 ||
          item.indexOf('[[cog]]') >= 0 ||
          item.indexOf('[[gear]]') >= 0 ||
          item.indexOf('[[refresh]]') >= 0 ||
          item.indexOf('[[spinner]]') >= 0
      ) {
        icon = item.replace(/\[\[(.*)\]\]/g, '<i class="fa fa-spin fa-$1"></i>');
      } else if (item.indexOf('[[loading]]') >= 0) {
        icon = '<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>';
      } else if (item.indexOf('[[handshake]]') >= 0) {
        icon = item.replace(/\[\[(.*)\]\]/g, '<i class="fa fa-handshake-o"></i>');
      }
      return icon;
    } else {
      return item;
    }
  };

  var postHtml = '\
    <p style="display:' + (ui.showNameOnTop?'block':'none') + ';font-weight: 900; background-color:' + ui.title.backgroundColor + '; color:' + ui.title.color + '" class="jj-title">' + name + '</p>\
  '
  var displayIntroHTML = (ui.showIntroMessage && ui.introMessage)?'block':'none';
  var introHTML = '<div style="display:' + displayIntroHTML + '" class="jj-intro">' + ui.introMessage + '</div>'
  var html = '\
  <div style="margin-top:10px">\
    <p style="background-color:' + ui.headline.backgroundColor + '; color:' + ui.headline.color + '" class="jj-title">' + name + '</p>\
    <table cellspacing="0" cellpadding="0" width="100%"> \
      <thead> \
        <tr>' + buildHeader() + '</tr> \
      </thead> \
      <tbody>' + buildTr() + '<tbody> \
    </table>\
  </div>';

  if (pLink && pLink.length === 36) {
    var iframeURL = '';
    var _l = getLocation(scriptURL);
    if (scriptURL.indexOf('https') >= 0) {
      var _h = _l.host.split(':')[0];
      iframeURL = 'https://' + _h + '/input-form.html?id=';
    } else {
      var _h = _l.host.split(':')[0];
      iframeURL = 'http://' + _h + ':8080/input-form.html?id=';
    }
    html = postHtml + introHTML + '<iframe id="jj-iframe" frameBorder="0" scrolling="no" src="' + iframeURL + pLink + '" width="100%" height="450"></iframe>' + html;
  }
  return html;
}

var scriptEle = document.getElementById('jj-noi-dung');
var scriptURL = scriptEle.src;

var l = getLocation(scriptURL);
var ap = l.protocol + '//' + l.host;
// console.log(ap)
var apiHost = '';

if (scriptURL.indexOf('https' >= 0)) {
  apiHost = l.protocol + '//' + l.host
} else {
  var tmpHost = l.host.split(':');
  if (tmpHost.length === 1) {
    apiHost = tmpHost.join(':') + ':8080';
  } else {
    tmpHost[1] = '8080';
    apiHost = tmpHost.join(':');
  }
  apiHost = 'http://' + apiHost;
}

var q = getParamFromUrl(scriptURL);
var pLink = q.link;
var pTable = q.ptable;

var embeded = document.createElement('div');
embeded.setAttribute('id', 'jj-embeded');

scriptEle.parentNode.insertBefore(embeded, scriptEle);

document.write('<link href="' + ap + '/render.css" rel="stylesheet" type="text/css">');
document.write('<link rel="stylesheet" href="https://unpkg.com/font-awesome@4.7.0/css/font-awesome.min.css">');

function loadData(cb) {
  if (!window['axios']) {
    if (cb) {
      cb();
    }
    return;
  }
  // axios.defaults.headers.common['Authorization'] = '';
  axios.get(apiHost + '/api/PredictTable/' + pTable).then(function(res) {
    var jsonObj = res.data;
    var table = JSON.parse(jsonObj.value);

    var keywords = (table.winKeywords || '').split(',').map(v => v.trim().toLowerCase()).filter(v => v);
    var isWinRow = {};
    table.data = table.data.slice(0, 30)
    table.data.forEach((row, ri) => {
      const isWin = row.reduce((pre, cur) => !!pre || cur === '__WIN__' || keywords.filter(v => cur.toLowerCase().indexOf(v) >= 0).length > 0, false)
      if (isWin) {
        isWinRow[ri] = true;
      }
    });

    var innerHTML = buidHTML(jsonObj.name, table, {
      isWinRow: isWinRow,
    });
    embeded.innerHTML = innerHTML;
    if (cb) {
      cb();
    }
  });
};

function startTimer() {
  console.log('call timer');
  var ttl = 15 * 60 * 1000;
  if (!window['axios']) {
    ttl = 10;
  }
  setTimeout(function() {
    loadData(function() {
      startTimer();
    });
  }, ttl);
}

loadData();
startTimer();

// listen message from iframe
var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
var eventer = window[eventMethod];
var messageEvent = eventMethod == 'attachEvent' ? 'onmessage' : 'message';
eventer(messageEvent, function(e) {
  if (e.data) {
    try {
      var jsonObj = JSON.parse(e.data);
      var iframe = document.getElementById('jj-iframe');
      if (iframe) {
        if (jsonObj.action === 'resize') {
          var afterEdit = jsonObj.height + 'px';
          if (iframe.style.height !== afterEdit) {
            iframe.style.height = afterEdit;
          }
        }
      }
    } catch (e) {}
  }
}, false);
