import clock from "clock";
import document from "document";
import { preferences } from "user-settings";
import * as util from "../common/utils";
import { geolocation } from "geolocation";
import * as messaging from "messaging";
import { battery, charger } from "power";
import { HeartRateSensor } from "heart-rate";
import { me as appbit } from "appbit";
import { today } from "user-activity";

// Update the clock every second, to help track steps/battery
clock.granularity = "seconds";

// Get a handle on the <text> element 
const curTime = document.getElementById("curTime");
const amPm = document.getElementById("amPm");
const amPmShadow = document.getElementById("amPmShadow");
const curMonth = document.getElementById("curMonth");
const curDay = document.getElementById("curDay");
const clockShadow = document.getElementById("clockShadow");
const curTemp = document.getElementById("curTemp");
const curHumidity = document.getElementById("curHumidity");
var weatherData;
var img = document.getElementById("myImage");
const batLvl = document.getElementById("batLvl");
const heartRate = document.getElementById("heartRate");
const steps = document.getElementById("steps");
const calories = document.getElementById("calories");
const info = document.getElementsByClassName("info");
const weatherImg = document.getElementById("weatherImg");
const batImg = document.getElementById("batImg"); // Get icon image of battery
batImg.href = calcBatImg(); //Initialise battery image
let weatherLoad = false;

// Function Definition
function colorChange(temp) {
  if (temp < 32) { curTime.style.fill = 'white'; amPm.style.fill = 'white';
  } else if ( temp >= 32 && temp < 50 ) { curTime.style.fill = 'blue';  amPm.style.fill = 'blue';
  } else if ( temp >= 50 && temp < 60 ) { curTime.style.fill = 'green';  amPm.style.fill = 'green';
  } else if ( temp >= 60 && temp < 70 ) { curTime.style.fill = 'yellow';  amPm.style.fill = 'yellow';
  } else if ( temp >= 70 && temp < 80 ) { curTime.style.fill = 'orange';  amPm.style.fill = 'orange';
  } else if ( temp >= 80 && temp < 90 ) { curTime.style.fill = 'red';  amPm.style.fill = 'red';
  } else { curTime.style.fill = 'black'; amPm.style.fill = 'black'; } 
}

function backgroundChange(weather) {
  if (weather == 'Thunderstorm') { img.href = "images/thunder_temple_1.png";
  } else if (weather == 'Drizzle') { img.href = "images/drizzle_street.png";
  } else if (weather == 'Rain') { img.href = "images/rainy_street_1.png";
  } else if (weather == 'Snow') { img.href = "images/snowy_torii_1.png"; 
  } else if (weather == 'Mist') { img.href = "images/rainy_torii_1.png";
  } else if (weather == 'Smoke') { img.href = "images/smoke_and_ash.png"; 
  } else if (weather == 'Haze') { img.href = "images/rice_fog_1.png";
  } else if (weather == 'Dust') { img.href = "images/japan-dust.png";
  } else if (weather == 'Fog') { img.href = "images/rainbow_fog_1.png"; 
  } else if (weather == 'Sand') { img.href = "images/japan-sand.png";
  } else if (weather == 'Ash') { img.href = "images/smoke_and_ash.png"; 
  } else if (weather == 'Squall') { img.href = "images/thunder_tokyo_1.png";
  } else if (weather == 'Tornado') { img.href = "images/japan-tornado.png";
  } else if (weather == 'Clear') { img.href = "images/sunny_torii_2.png"; 
  } else if (weather == 'Clouds') { img.href = "images/cloudy_fuji_1.png";
  } else { img.href = "images/sunny_fuji_1.png"; }
}

function calcBatImg(batCharge) {
 if (batCharge > 88) { return "bat/bat-100.png";
 } else if (batCharge > 76) { return "bat/bat-88.png";
 } else if (batCharge > 64) { return "bat/bat-64.png";
 } else if (batCharge > 52) { return "bat/bat-52.png";
 } else if (batCharge > 40) { return "bat/bat-40.png";
 } else if (batCharge > 28) { return "bat/bat-28.png";
 } else if (batCharge > 16) { return "bat/bat-16.png";
 } else { return "bat/bat-5.png"; }
}

function showDate(evt){
  let todayDate = evt.date;
  let monthNum = todayDate.getMonth();
  let day = todayDate.getDate();
  let month = new Array();
  month[0] = "Jan";
  month[1] = "Feb";
  month[2] = "Mar";
  month[3] = "Apr";
  month[4] = "May";
  month[5] = "Jun";
  month[6] = "Jul";
  month[7] = "Aug";
  month[8] = "Sep";
  month[9] = "Oct";
  month[10] = "Nov";
  month[11] = "Dec";
 let monthName = month[monthNum];
  curMonth.text = monthName;
  curDay.text = day;
}

// Update the <text> element every tick with the current time
clock.ontick = (evt) => {
  // Assigns battery level
  batLvl.text = (Math.floor(battery.chargeLevel) + "%");
  if (charger.connected) {
    batImg.href = "bat/bat-charge.png";
  } else {
    // Determine which battery image needs to be shown.
    batImg.href = calcBatImg(battery.chargeLevel);
  }
  
  //Assigns steps
  if (appbit.permissions.granted("access_activity")) {
     steps.text = today.adjusted.steps;
     calories.text = today.adjusted.calories;
  }
  
  showDate(evt);
  
  let todayDate = evt.date;
  let hours = todayDate.getHours();
  if (preferences.clockDisplay === "12h") {
    // 12h format
    if(hours / 12 >= 1){
      amPm.text = "PM"; amPmShadow.text = "PM";
    }
    else{
        amPm.text = "AM"; amPmShadow.text = "AM";
      }
    hours = hours % 12 || 12;
  } else {
    // 24h format
    hours = util.zeroPad(hours);
    amPm.text = "";
    amPmShadow.text = "";
  }
  let mins = util.zeroPad(todayDate.getMinutes());
  curTime.text = `${hours}:${mins}`;
  clockShadow.text = `${hours}:${mins}`;
  
  // Check the Weather
  function fetchWeather() {
    if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) {
      // Send a command to the companion
      messaging.peerSocket.send({
        command: "weather"
      });
    }
  }

  function processWeatherData(data) { 
    colorChange(data.temperature);
    weatherImg.href = "weatherIcons/"+ data.icon + "@2x.png";
    curTemp.text = `${Math.floor(data.temperature)} °F`;
    curHumidity.text = `${data.humidity}%: Humidity`;
    backgroundChange(data.forecast);
  }

  messaging.peerSocket.addEventListener("open", (evt) => { fetchWeather(); });

  messaging.peerSocket.addEventListener("message", (evt) => {
    if (evt.data) { processWeatherData(evt.data); } });

  messaging.peerSocket.addEventListener("error", (err) => { console.error(`Connection error: ${err.code} - ${err.message}`); });

  // Fetch the weather every 10 minutes, openweathermap updates every 10 minutes
  setInterval(fetchWeather, 10 * 1000 * 60);
  
}
  
//Assigns the heart rate to our label
if (HeartRateSensor) {
   console.log("This device has a HeartRateSensor!");
   const hrm = new HeartRateSensor();
   hrm.addEventListener("reading", () => { 
     heartRate.text = `${hrm.heartRate}`;
     if (hrm.heartRate > 99) { heartRate.style.fontSize = 22; 
     } else { heartRate.style.fontSize = 28; }
   });
   hrm.start();
} 