import PushNotification from 'react-native-push-notification';

export function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();

  return 'Today, ' + day + ' ' + monthNames[monthIndex];
}

export function scheduleLocalNotification(message, date, id, payload) {
  //message: type String
  //date: type String  format 'YYYY-MM-DD HH:mm' (NOTIFICATION_DATE_TIME_FORMAT)

  //construct the notification parameters
  // const fireDate = moment(date, NOTIFICATION_DATE_TIME_FORMAT).toDate();
  const fireDate = date
  const notification = {
    id: id, //for android cancel notification (must be stringified number)
    message,
    number: 0, //necessary for iOS cancellation (not sure why)
    date: fireDate,
    //for android only
    data: JSON.stringify(payload),
    repeatType: 'day'
  };

  //schedule the notification
  PushNotification.localNotificationSchedule(notification);
}

export function appointmentNotification(message, date, id, payload) {
  //message: type String
  //date: type String  format 'YYYY-MM-DD HH:mm' (NOTIFICATION_DATE_TIME_FORMAT)

  //construct the notification parameters
  // const fireDate = moment(date, NOTIFICATION_DATE_TIME_FORMAT).toDate();
  const fireDate = date
  const notification = {
    id: id, //for android cancel notification (must be stringified number)
    message,
    number: 0, //necessary for iOS cancellation (not sure why)
    date: fireDate,
    //for android only
    data: JSON.stringify(payload),
  };

  //schedule the notification
  PushNotification.localNotificationSchedule(notification);
}

export function cancleNotification(id) {
  PushNotification.cancelLocalNotifications({ id: id });
}

export function generateID() {
  let d = new Date().getTime();
  let id = 'xxxy'.replace(/[xy]/g, function (c) {
    let r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(5);
  });

  return id;
}

export const futch = (url, opts = {}, onProgress) => {
  console.log(url, opts)
  return new Promise((res, rej) => {
    var xhr = new XMLHttpRequest();
    xhr.open(opts.method || 'get', url);
    for (var k in opts.headers || {})
      xhr.setRequestHeader(k, opts.headers[k]);
    xhr.onload = e => res(e.target);
    xhr.onerror = rej;
    if (xhr.upload && onProgress)
      xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
    xhr.send(opts.body);
  });
}