"use strict";

/* Convert a Date object to a work-week #, following Intel's
 * methodology with the exception that we list WW53'(xx) for 
 * December dates that would be in WW01'(xx+1) */
function intelDateToWW(date) {
  if (!(date instanceof Date)) {
    return "N/A: " + date;
  }
  var jan1 = new Date(date);
  jan1.setMonth(0, 1);
  var day = jan1.getDay();
  /* 0 = Sunday */
  
  /* Determine the start of WW01 in # of seconds since
   * Jan 1, 1970 00:00 GMT */
  var time = (jan1.getTime() / 1000) - (24 * 60 * 60) * (day + 1);
  
  /* Determine how far into the year the requested time
   * is with WW01 00:00 as the base. */
  var delta = (date.getTime() / 1000) - time;
  
  var weeks = Math.ceil(delta / (24 * 60 * 60 * 7)),
    year = date.getFullYear();
  
  if (weeks > 52) {
    weeks -= 52;
    year++;
  }

  return "WW" + (weeks < 10 ? "0" : "") + weeks + "'" + (year % 100);
}

/* Convert an Intel WW to the date of Friday of that work week */
function intelWWToDate(workweek, startOfWeek) {
  if (!/^ww/i.exec(workweek)) {
    workweek = "ww" + workweek;
  }
  /*                                    1       2 3            */
  var parts = ("" + workweek).match(/^ww([0-9]+)\s*('([0-9]+))?$/i);
  if (!parts) {
    return "N/A: " + workweek;
  }
  var year = parseInt(parts[3] || new Date().getFullYear()),
    week = parseInt(parts[1].replace(/^0/, ""));
  if (year < 1000) {
    year += 2000;
  }
  
  var jan1 = new Date(year, 0, 1, 0, 0, 0, 0);
  
  /* Rebase the returned date to Friday in the target WW */
  jan1.setDate((week * 7) - (jan1.getDay() + (startOfWeek ? 5 : 1)));
  
  return jan1;
}

export default {
  intelDateToWW,
  intelWWToDate
};