"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
// GHS — ID's en nummers: één plek.
//   ghsId(prefix)      intern ID: uniek, onveranderlijk, nooit op papier (bv. 'pl' + tijd + toeval).
//   ghsNummer(soort)   zichtbaar nummer (OFF-2026-1234): jaar uit de datum, teller loopt altijd door,
//                      nooit lager dan wat al bestaat (ook werkbonnen per moment, vorige facturen).
//   ghsPersoon(x)      gebruiker of technieker uit id, naam of oud id.
// PRODUCTIE: ghsNummer is de enige plek die naar de server moet — één atomische teller per soort.
// Zolang de teller in de browser staat, kunnen twee pc's hetzelfde nummer uitreiken.
(function () {
  var GHS_ID_SOORTEN = {
    OFF: {
      label: 'Offerte',
      key: 'ghs_off_seq_v1'
    },
    LOS: {
      label: 'Los werk',
      key: 'ghs_los_seq_v1'
    },
    WB: {
      label: 'Werkbon',
      key: 'ghs_wb_seq_v1'
    },
    FAC: {
      label: 'Factuur & voorschot',
      key: 'ghs_fac_seq_v1'
    },
    CN: {
      label: 'Creditnota',
      key: 'ghs_cn_seq_v1'
    },
    TS: {
      label: 'Ticket',
      key: 'ghs_ts_seq_v1',
      pad: 4
    }
  };
  var idRnd = function idRnd(n) {
    try {
      var a = new Uint8Array(n);
      crypto.getRandomValues(a);
      return _toConsumableArray(a).map(function (b) {
        return (b % 36).toString(36);
      }).join('');
    } catch (e) {
      return Math.random().toString(36).slice(2, 2 + n).padEnd(n, '0');
    }
  };
  var idLaatst = 0;
  var ghsId = function ghsId() {
    var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'x';
    var t = Date.now();
    if (t <= idLaatst) t = idLaatst + 1;
    idLaatst = t;
    return String(prefix) + t.toString(36) + idRnd(4);
  };
  var idJaar = function idJaar() {
    return String(window.GHS_TODAY || new Date().toISOString()).slice(0, 4);
  };
  var idNr = function idNr(s) {
    var n = parseInt(String(s || '').split('-').pop(), 10);
    return isNaN(n) ? 0 : n;
  };
  /* Het hoogste nummer dat al bestaat, over alle bronnen van die soort heen. */
  var ghsHoogsteNummer = function ghsHoogsteNummer(soort) {
    var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      contacts = _ref.contacts,
      tickets = _ref.tickets;
    var max = 0;
    var pak = function pak(s) {
      var n = idNr(s);
      if (n > max) max = n;
    };
    (contacts || []).forEach(function (c) {
      if (soort === 'OFF') (c.deals || []).forEach(function (d) {
        if (!d.service && !d.los) pak(d.ref);
      });
      if (soort === 'LOS') (c.deals || []).forEach(function (d) {
        if (d.los) pak(d.ref);
      });
      if (soort === 'WB') Object.keys(c.werkbonState || {}).forEach(function (r) {
        var ws = c.werkbonState[r];
        if (ws && ws.werkbon) pak(ws.werkbon.nr);
        var b = window.ghsWbBonnen ? window.ghsWbBonnen(c, r) : null;
        Object.values(b || {}).forEach(function (x) {
          return pak(((x || {}).werkbon || {}).nr);
        });
      });
      if (soort === 'FAC') Object.values(c.facturatieState || {}).forEach(function (fs) {
        if (!fs) return;
        pak(fs.factuurNr);
        if (fs.voorschot) pak(fs.voorschot.factuurNr);
        (fs.vorigeFacturen || []).forEach(function (v) {
          return pak(v.factuurNr || v.nr);
        });
      });
      if (soort === 'CN') Object.values(c.facturatieState || {}).forEach(function (fs) {
        return ((fs || {}).creditnotas || []).forEach(function (x) {
          return pak(x.nr);
        });
      });
    });
    if (soort === 'TS') (tickets || []).forEach(function (t) {
      return pak(t.nr);
    });
    return max;
  };
  var ghsNummer = function ghsNummer(soort) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var def = GHS_ID_SOORTEN[soort];
    if (!def) throw new Error('Onbekende nummersoort: ' + soort);
    var seq = 0;
    try {
      seq = parseInt(localStorage.getItem(def.key) || '0', 10) || 0;
    } catch (e) {}
    var next = Math.max(ghsHoogsteNummer(soort, opts) + 1, seq + 1, opts.min || 1001);
    try {
      localStorage.setItem(def.key, String(next));
    } catch (e) {}
    return "".concat(soort, "-").concat(idJaar(), "-").concat(def.pad ? String(next).padStart(def.pad, '0') : next);
  };
  var ghsPersoon = function ghsPersoon(x) {
    if (!x) return null;
    var k = _typeof(x) === 'object' ? x.id || x.name || x.naam : x;
    var users = [];
    try {
      users = window.ghsAlleGebruikers ? window.ghsAlleGebruikers() || [] : [];
    } catch (e) {}
    return [].concat(_toConsumableArray(users), _toConsumableArray(window.USERS || []), _toConsumableArray(window.PLANNING_CREW || [])).find(function (u) {
      return u && (u.id === k || u.legacy === k || u.name === k);
    }) || null;
  };
  Object.assign(window, {
    GHS_ID_SOORTEN: GHS_ID_SOORTEN,
    ghsId: ghsId,
    ghsNummer: ghsNummer,
    ghsHoogsteNummer: ghsHoogsteNummer,
    ghsPersoon: ghsPersoon
  });
})();