const http = require('http');
const ZHerdsman = require('zigbee-herdsman');
const { zigbeeUsb, zigbeeDbPath, sonosIp } = require('../config');
const zigbeeConfig = require('../zigbee_config');

const { Sonos } = require('sonos')
const device = new Sonos(sonosIp);

let volumeTimerHandle = null;

console.log(zigbeeUsb, zigbeeDbPath, zigbeeConfig);

const zserver = new ZHerdsman(zigbeeUsb, { dbPath: zigbeeDbPath});

zserver.on('ready', function () {
  console.log('Zigbee is ready.');
});

zserver.on('permitJoining', function (joinTimeLeft) {
  console.log(joinTimeLeft);
});


zserver.start(function (err) {
  if (err)
    console.log(err);
});

zserver.on('ind', function (msg) {
  switch (msg.type) {
    case 'devIncoming':
      console.log('Device: ' + msg.data + ' joining the network!');
      msg.endpoints.forEach(function (ep) {
        console.log(JSON.stringify(ep.dump(), null, '\t'));
      });
      break;
    case 'devChange':
      console.log('Dev Change: ' + msg.data);
      break;
    case 'cmdOn':
      handleOnOff(msg.endpoints[0].device.ieeeAddr, true);
      break;
    case 'cmdOff':
      handleOnOff(msg.endpoints[0].device.ieeeAddr, false);
      break;
    case 'cmdMoveWithOnOff':
      handleVolumeChangeStart(true);
      break;
    case 'cmdStopWithOnOff':
      handleVolumeChangeStop();
      break;
    case 'cmdMove':
      handleVolumeChangeStart(false);
      break;
    default:
      console.log('Unknown');
      console.log(msg);
      break;
  }
});

function handleOnOff(address, isOn) {
  console.log(address, isOn);
  zigbeeConfig.devices.forEach(device => {
    if (device.ieeeAddr == address) {
      const endpoints = isOn ? device.endpointsOn : device.endpointsOff;
      endpoints.forEach(url => {
        console.log(url);
        http.get(url, (res) => {
          console.log(res.statusCode)
        }).on('error', err => {
          console.log(err);
        });
      });
    }
  });
}

function changeVolume(percent) {
  device.getVolume()
    .then(volume => device.setVolume(volume + percent < 0 ? 0 : volume + percent))
    .catch(err => console.log(err));
}

function handleVolumeChangeStart(isVolumeUp) {
  if (volumeTimerHandle != null) {
    console.log("Something is really wrong");
    clearInterval(volumeTimerHandle);
  }

  changeVolume(isVolumeUp ? 5 : -10);

  volumeTimerHandle = setInterval(() => {
    changeVolume(isVolumeUp ? 5 : -10);
  }, 1000);
}

function handleVolumeChangeStop(isVolumeUp) {
  clearInterval(volumeTimerHandle);
  volumeTimerHandle = null;
}

module.exports = {
  permitJoin: function(timeSeconds) {
    zserver.permitJoin(timeSeconds);
  },
  light: function(name, options) {
    
    return true;
  },
};
@@ -287,16 +287,52 @@
  = null;
+%0Alet safetyVolumeTimerHandle = null;
 %0A%0Aconsol
@@ -2327,16 +2327,105 @@
 );%0A  %7D%0A%0A
+  if (safetyVolumeTimerHandle != null) %7B%0A    clearTimeout(safetyVolumeTimerHandle);%0A  %7D%0A%0A
   change
@@ -2444,23 +2444,22 @@
 umeUp ? 
-5
+2
  : -
-10
+4
 );%0A%0A  vo
@@ -2530,30 +2530,267 @@
 p ? 
-5
+2
  : -
-1
+4);%0A  %7D, 50
 0);%0A
+%0A
   
+// Incase button release message get lost for some reason, stop change after 5s if isVolumeUp%0A  if (isVolumeUp) %7B%0A    safetyVolumeTimerHandle = setTimeout(() =%3E %7Bconsole.log('saftey off'); clearInterval(volumeTimerHandle);
 %7D, 
-1
+5
 000);%0A
+  %7D%0A
 %7D%0A%0Af
@@ -2872,17 +2872,92 @@
 dle);%0A  
-v
+clearTimeout(safetyVolumeTimerHandle);%0A  volumeTimerHandle = null;%0A  safetyV
 olumeTim

Add safety timer if button release msg is lost so that we don't max out the speakers on full volume