var _ = require("lodash");
var QRCode = require("qrcode");
const moment = require("moment");

const config = require("../config");
const { colourNameToHex } = require("./color.helper");

const luma = (color) => { // color can be a hx string or an array of RGB values 0-255
  const rgb = (typeof color === 'string') ? hexToRGBArray(color) : color;
  return (0.2126 * rgb[0]) + (0.7152 * rgb[1]) + (0.0722 * rgb[2]); // SMPTE C, Rec. 709 weightings
}

const hexToRGBArray = (color) => {
  if (color.length === 3)
    color = color.charAt(0) + color.charAt(0) + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2);
  else if (color.length !== 6)
    console.debug('Invalid hex color: ' + color);

  const rgb = [];
  for (var i = 0; i <= 2; i++)
    rgb[i] = parseInt(color.substr(i * 2, 2), 16);
  return rgb;
}

const calculateContrastingColor = (color) => {
  var _color = '#000';

  if (typeof color !== 'string') {
    return _color;
  }

  if (color.charAt(0) !== '#') {
    _color = colourNameToHex(color);
  }

  _color = _color.replace('#', '');
  return (luma(_color) >= 165) ? '#000' : '#fff';
}


module.exports.getInscriptionQRCodeUrl = function (inscriptionId) {
  return encodeURI(`${config.server.public_url}/inscriptions/${inscriptionId}/qrimage`);
};

/* params = {
    code: 'xxxx',
    date: 'date-time',
    name: 'xxxx',
    surname: 'xxxx',
    color: '#ff',

} */

module.exports.getInscriptionQRCode = function (params) {
  return new Promise(function (resolve, reject) {
/*    var texto =
      _.padStart(params.code, 4, "0") +
      "\n" +
      moment(params.date).format("DD/MM/YY HH:mm ") +
      params.name +
      " " +
      params.surname;
*/
    var texto =
      _.padStart(params.code, 4, "0");

    var options = {
      errorCorrectionLevel: "M",
    };

    if (params.color) {
      options = _.assign(options, {
        color: {
          light: params.color ? colourNameToHex(params.color) : "#000000",
          dark: calculateContrastingColor(params.color), //"#ffffff",
        },
      });
    }

    QRCode.toDataURL(texto, options, function (err, qrcode) {
      if (err) resolve("");
      //            console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode);
      resolve(qrcode);
    });
    /*
        QRCode.toString(texto, options, function (err, qrcode) {
            if (err) resolve('');
            console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + qrcode);
            resolve(qrcode);
        });
*/
  });
};

module.exports.generateQRConfig = function (params) {
  let qrConfig = null;
  if (params) {
    qrConfig = {
      name: params.name,
      surname: params.surname,
      date: params.date_inscription,
      code: params.code_ticket,
      color: params.color,
    };
  }

console.log('generateQRConfig<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<', params, qrConfig);

  return qrConfig;
};

