getDayFromWestern static method

TibetanCalendar getDayFromWestern(
  1. DateTime date
)

GET DAY FROM WESTERN

Implementation

static TibetanCalendar getDayFromWestern(DateTime date) {
  // const date = new Date(wYear, wMonth - 1, wDay);
  var wYear = date.year;
  var jd = julianFromUnix(date);
  var tibYears = [wYear + YEAR_DIFF - 1, wYear + YEAR_DIFF + 1];

  var monthCounts = [];
  tibYears.forEach((y) {
    monthCounts.add(
        monthCountFromTibetan({'year': y, 'month': 1, 'isLeapMonth': true}));
  });

  /* var monthCounts = tibYears.map((y) {
    return monthCountFromTibetan(
        {'year': y, 'month': 1, 'isLeapMonth': true});
  });*/
  //todo check list or map
  var trueDate = [];
  monthCounts.forEach((element) {
    trueDate.add((1 + 30 * element));
  });
  var jds = [];
  trueDate.forEach((element) {
    jds.add(julianFromTrueDate(element));
  });
  //   croak "Binary search algorithm is wrong" unless $jd1 <= $jd && $jd <= $jd2;
  while (trueDate[0] < trueDate[1] - 1 && jds[0] < jds[1]) {
    var nTrueDate = ((trueDate[0] + trueDate[1]) / 2).floor();
    var njd = julianFromTrueDate(nTrueDate);
    if (njd < jd) {
      trueDate[0] = nTrueDate;
      jds[0] = njd;
    } else {
      trueDate[1] = nTrueDate;
      jds[1] = njd;
    }
  }

  /// so we found it;
  num winnerJd;
  num winnerTrueDate;

  /// if the western date is the 1st of a doubled tib. day, then jd[0] == jd - 1 and
  /// jd[1] == jd + 1, and the corresponding tib. day number is the one from jd[1].
  if (jds[0] == jd) {
    winnerJd = jds[0]; // eslint-disable-line prefer-destructuring
    winnerTrueDate = trueDate[0]; // eslint-disable-line prefer-destructuring
  } else {
    winnerJd = jds[1]; // eslint-disable-line prefer-destructuring
    winnerTrueDate = trueDate[1]; // eslint-disable-line prefer-destructuring
  }

  /// figure out the real tib. date: year, month, leap month, day number, leap day.
  var isLeapDay = winnerJd > jd;
  var monthCount = ((winnerTrueDate - 1) / 30).floor();
  var day;
  if (winnerTrueDate % 30 == 0) {
    day = 30;
  } else {
    day = winnerTrueDate % 30;
  }

  var _a = getMonthFromMonthCount(monthCount);
  var year = _a['year'];
  var month = _a['month'];
  var isLeapMonth = _a['isLeapMonth'];
  return getDayFromTibetan({
    'year': year,
    'month': month,
    'isLeapMonth': isLeapMonth,
    'day': day,
    'isLeapDay': isLeapDay,
  });
}