'use strict';
var tg = tg || {};

var pwa = pwa || {};

$.fn.isInViewport = function() {
  var elementTop = $(this)
    .offset()
    .top;
  var elementBottom = elementTop + $(this)
    .outerHeight();
  var viewportTop = $(window)
    .scrollTop();
  var viewportBottom = viewportTop + $(window)
    .height();
  return elementBottom > viewportTop && elementTop < viewportBottom;
};
// A cutomiser par client
tg.plan = {
  action: [
    { selector: '*[data-tgmd]', action: 'click' }
  ],
  showed: [{ selector: '*[data-tgmd="partietext"]' }]
};
tg.content = [];
if(localStorage.getItem('tgcontent')) tg.content = JSON.parse(localStorage.getItem('tgcontent'));
tg.listen = function() {
  //$('.data-tgmd').onclick(function(){logger.info("test")})
  tg.plan.action.forEach(e => {
    $(e.selector)
      .on(e.action, function() {
        //envoie un poste avec tag et onclick
        logger.info('declenche ' + e.action + ' sur ' + e.selector + 'avec valeur de ' + $(e.selector)
          .val());
        tgcontent.push([e.action, e.selector, $(e.selector)
          .val(), Date.now()
        ])
      })
  });
  $(window)
    .on('resize scroll', function() {
      tg.plan.showed.foreach((e, i) => {
        if($(e.selector)
          .isInViewport) {
          //marque l'affichage
          tg.plan.showed[i].timeon = Date.now();
        } else {
          if(tg.plan.showed[i].timeon) {
            //affichage qui passe of

          }
        }
      })
    })
  $(window)
    .unload(function() {
      // on quitte la fenetre
      tg.action({ tgcontent: tg.content })

    })
}

tg.getUrlParams = function(url) {
  var params = {};
  (url + '?')
  .split('?')[1].split('&')
    .forEach(function(pair) {
      pair = (pair + '=')
        .split('=')
        .map(decodeURIComponent);
      if(pair[0].length) {
        params[pair[0]] = pair[1];
      }
    });
  return params;
};

tg.setCookie = (key, value) => {var expires = new Date();

  expires.setTime(expires.getTime() + 365 * 24 * 60 * 60 * 1000);
  document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
};

tg.getCookie = (key) => {
  var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
  return keyValue ? keyValue[2] : null;
}

tg.setlocalS = (info) => {
  let r = localStorage.getItem('r');
  logger.info(r);
  if(r == undefined || !r) {
    r = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
    localStorage.setItem('r', r);
    tg.setCookie(r, r);
  }
  if(info.id) {
    localStorage.setItem('id', info.id);
  }
  logger.info(info)
  tg.action(info)
}
tg.agreement = () => {
  if(tg.getCookie('accept') == undefined) {
    $('.cookiewarning')
      .css('display', 'inline-block');
  }
  $('button.acceptcookie')
    .on('click', function() {
      let accord = "ok"
      if($(this)
        .attr('data-accord')) {
        accord = $(this)
          .attr('data-accord')
      }
      tg.setCookie('accept', accord);
      $('.cookiewarning')
        .css('display', 'none');
    });
}
tg.action = (post) => {
  post.tit = encodeURIComponent(document.title);
  if(localStorage.getItem('r')) post.r = localStorage.getItem('r');
  if(localStorage.getItem('id')) post.id = localStorage.getItem('id');
  if(localStorage.getItem('accept')) post.accept = localStorage.getItem('accept');
  logger.info('post content', post);
  let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {};
  xhttp.open(
    'POST',
    `${pwa.urlapixtribe}/tags/${pwa.tribeid}`,
    true
  );
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhttp.onload = function(post) {
    if(xhttp.status != 200) {
      //pb d'acces on stock tag:
      localStorage.setItem('tgcontent', JSON.stringify(tg.content));
    } else {
      //envoyer on vide tgcontent
      localStorage.setItem('tgcontent', '[]')
    }
  }
  xhttp.send(JSON.stringify(post));
};

$(document)
  .ready(function() {
    if(!pwa.tribeid) {
      pwa.urlapixtribe = 'https://api' + $('#mxp')
        .attr('data-destin') + '.maildigit.fr';
      pwa.tribeid = $('#mxp')
        .attr('data-tribeid');
    }
    logger.info('pwa', pwa)
    logger.info('url', window.location.href)
    logger.info('info', tg.getUrlParams(window.location.href))
    tg.setlocalS(tg.getUrlParams(window.location.href));
    tg.agreement();
  });
