'use strict';

var UULE = (function () {

  var SECRET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';

  function b64(str) {
    var bytes = new TextEncoder().encode(str);
    var bin = '';
    for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
    return btoa(bin);
  }

  function named(canonical) {
    canonical = (canonical || '').trim();
    if (!canonical) return '';
    var lenChar = SECRET[canonical.length % 64];
    return 'w+CAIQICI' + lenChar + b64(canonical);
  }

  function coordPayload(lat, lng) {
    var latE7 = Math.round(Number(lat) * 1e7);
    var lngE7 = Math.round(Number(lng) * 1e7);
    if (!isFinite(latE7) || !isFinite(lngE7)) return null;
    return 'role: 1\n' +
      'producer: 12\n' +
      'provenance: 6\n' +
      'timestamp: ' + (Date.now() * 1000) + '\n' +
      'latlng {\n' +
      '  latitude_e7: ' + latE7 + '\n' +
      '  longitude_e7: ' + lngE7 + '\n' +
      '}\n' +
      'radius: -1\n';
  }

  function coords(lat, lng) {
    var p = coordPayload(lat, lng);
    return p ? 'a+' + b64(p) : '';
  }

  function xgeo(lat, lng) {
    var p = coordPayload(lat, lng);
    return p ? 'a ' + b64(p) : '';
  }

  return { named: named, coords: coords, xgeo: xgeo };
})();

if (typeof module !== 'undefined' && module.exports) module.exports = UULE;
