angular.module('ff9cert.services', [])

.factory('CertificateService', function($http, EVENTBRITE, WORKSHOPS){
  var get_attendee = function(barcode) {
    var attendee_id = barcode.substring(9, 18);

    return $http.get(EVENTBRITE.api + '/events/' + EVENTBRITE.event_id + '/attendees/' + attendee_id + '/?token=' + EVENTBRITE.token)
    .then((response) => {
      return Promise.resolve(response);
    })
    .catch((response) => {
      var attendee_id = barcode.substring(9, 19);
      return $http.get(EVENTBRITE.api + '/events/' + EVENTBRITE.event_id + '/attendees/' + attendee_id + '/?token=' + EVENTBRITE.token);
    })
    .then((response) => {
      return Promise.resolve(response.data);
    })
    .catch((response) => {
      console.log(response);
    });
  };

  var generate_pdf = function(name, ticket){
    convertFileToDataURLviaFileReader('./assets/cert/cert.jpg', certuri => {
      var cert = new jsPDF('l', 'mm', [270.933333333, 209.55]);

      cert.addImage(certuri, 'PNG', 0, 0, 270.933333333, 209.55);

      cert.addFont('Acumin-Pro-Black.ttf', 'AcuminPro', 'black');
      cert.addFont('Inovato-Regular.ttf', 'Inovato', 'regular');
      cert.setTextColor(0, 97, 106);

      cert.setFont('AcuminPro', 'black');
      cert.setFontSize(48);
      var splitName = cert.splitTextToSize(name.toUpperCase(), 175);
      console.log(splitName);
      var x = 16;
      var y = 35
      splitName.forEach(namePart => {
        cert.text(namePart, x, y);
        y += 21;
      });

      // if(ticket.split(' - ')[0] === 'Track 1') {
      //   ticket = ticket.split(' - ')[1] + " with TJ Monserrat";
      // } else if(ticket.split(' - ')[0] === 'Track 2') {
      //   ticket = ticket.split(' - ')[1] + " with Drei Alquiros";
      // } else if(ticket.split(' - ')[0] === 'Track 3') {
      //   ticket = ticket.split(' - ')[1] + " with Richard Parayno";
      // }

      ticket = ticket.split(' - ')[1];

      cert.setFont('Inovato', 'regular');
      cert.setFontSize(17.2);
      cert.text(ticket, 16.75, 131.5);
      
      cert.save(name + '.pdf');
    });
  };

  function convertFileToDataURLviaFileReader(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      var reader = new FileReader();
      reader.onloadend = function() {
        callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  }

  return {
    get_attendee: get_attendee,
    generate_pdf: generate_pdf
  };
});
