import fs from 'fs'
import path from 'path';

// https://stackoverflow.com/questions/19700283/how-to-convert-time-in-milliseconds-to-hours-min-sec-format-in-javascript
function parseMillisecondsIntoReadableTime(milliseconds){
  //Get hours from milliseconds
  var hours = milliseconds / (1000*60*60);
  var absoluteHours = Math.floor(hours);
  var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
  //Get remainder from hours and convert to minutes
  var minutes = (hours - absoluteHours) * 60;
  var absoluteMinutes = Math.floor(minutes);
  var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;
  //Get remainder from minutes and convert to seconds
  var seconds = (minutes - absoluteMinutes) * 60;
  var absoluteSeconds = Math.floor(seconds);
  var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
  return h + ':' + m + ':' + s;
}


let visits = 0;
let timeSpentMs = 0;

const placeNamePatterns = ['Interesting place', 'Interesting place with another name']

const dataDirPath = './data';
const yearsDirs =  fs.readdirSync(dataDirPath);

yearsDirs.forEach((yearDir) => {
  if (yearDir.length !== 4) {
    return;
  }

  let visitsYear = 0;
  let timeSpentYearMs = 0;

  const yearDirPath = path.join(dataDirPath, yearDir);
  const filesInYearDir =  fs.readdirSync(yearDirPath);

  filesInYearDir.forEach((filename) => {
  const filePath = path.join(yearDirPath, filename);
  const data = fs.readFileSync(filePath, 'utf8');
  const timelineObjects = JSON.parse(data).timelineObjects;
  for (const timelineObject of timelineObjects) {
    if (timelineObject.placeVisit) {
      const placeVisit = timelineObject.placeVisit.location.name;
      const otherCandidateLocations = timelineObject.placeVisit.otherCandidateLocations;
      if (placeNamePatterns.some((pattern) => placeVisit?.includes(pattern)) || otherCandidateLocations?.some((location) => placeNamePatterns.some((pattern) => location.name?.includes(pattern)))) {
        const duration = timelineObject.placeVisit.duration;
        const start = new Date(duration.startTimestamp);
        const end = new Date(duration.endTimestamp);
        timeSpentYearMs = timeSpentYearMs + (end - start);
        visitsYear++;
      }
    }
  }
  });

  visits = visits + visitsYear;
  timeSpentMs = timeSpentMs + timeSpentYearMs;

  if (visitsYear === 0) {
    console.log(yearDir, 'no visits')
    console.log('\n')
    return;
  }

  console.log(yearDir)
  console.log(visitsYear, 'visits')
  console.log(parseMillisecondsIntoReadableTime(timeSpentYearMs), 'time spent')
  const average = timeSpentYearMs / visitsYear;
  console.log(parseMillisecondsIntoReadableTime(average), 'average time spent per visit')
  console.log('\n')
});


console.log('Total')
console.log(visits, 'visits')
console.log(parseMillisecondsIntoReadableTime(timeSpentMs), 'time spent')