var Manual = {};

Manual.id = "manual";

Manual.SpeedValue = '';

Manual.setSpeedValuetext = '';

Manual.grayscaleFlag = ''

Manual.aviodFlag = '';

Manual.followFlag = '';

Manual.ultrasonicFlag = '';

Manual.mileageObj = {};

Manual.mileageValue = 0;

Manual.ultrasonicDist = 1000;

Manual.sendValue = {
  'RC':'off',  // remote control  rest
  'GS': "off", // 巡线模块  'off'
  'RD':'off',  // 雷达  'off'
  'OA':'off',  // 避障  'off'
  'OF':'off',  // 跟随  'off'
  'TL':['off',400], // 巡线value  ['off', 400]
  'CD':['off',110], // 悬崖  ['off',110]
  'PW':1,  // 调速功率  50
  'SR':0,  // 复位  off
  'ST':'off', // 系统信息  'off'
  'US':['off',0],  // 超声波设置  ['off', 0]
  'MS':['off',4,0] // 测速设置  ['off', 1, 0]
}

/*
'RC':'off', // remote control rest
'GS': "off", // line-following module 'off'
'RD':'off', // radar 'off'
'OA':'off', // obstacle avoidance 'off'
'OF':'off', // follow mode 'off'
'TL':['off',400], // line-following value ['off', 400]
'CD':['off',110], // cliff detection ['off',110]
'PW':1, // speed control power 50
'SR':0, // reset 'off'
'ST':'off', // system information 'off'
'US':['off',0], // ultrasonic sensor setting ['off', 0]
'MS':['off',4,0] // speed measurement setting ['off', 1, 0]
*/
/*
send_dict = {
  'GS':[0,0,0],  // 巡线value
  'US':[angle, distance], // 超声波value
  'MS':[0,min], // 测速值
  'ST':{'a':1} // 系统信息value
}
*/
/*
send_dict = {
'GS':[0,0,0], // line-following value
'US':[angle, distance], // ultrasonic sensor value
'MS':[0,min], // speed measurement value
'ST':{'a':1} // system information value
}
*/

Manual.show = function () {
  document.querySelector('#manualContent').style.display = 'block';
  document.querySelector('#header').style.display = 'block';
  document.querySelector('.menu').style.display = 'block';
  // Manual.setUltrasonic();
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
}

Manual.hide = function () {
  document.querySelector('#manualContent').style.display = 'none';
  document.querySelector('#header').style.display = 'none';
  document.querySelector('.menu').style.display = 'none';
  Manual.menuItemClick("reset");
  Manual.sendValue = {
    'RC':'off',  // remote control
    'GS': "off", // 巡线模块
    'RD':'off',  // 雷达
    'OA':'off',  // 避障
    'OF':'off',  // 跟随
    'TL':['off',400], // 巡线value
    'CD':['off',110], // 悬崖
    'PW':50,  // 调速功率
    'SR': 'off',  // 复位
    'ST':'off', // 系统信息
    'US':['off',0],  // 超声波设置
    'MS':['off',1,0] // 测速设置
  }
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
  $('.ultrasonic_dot_block').html('');
}

Manual.setSpeedListener = function() {
  var speedSlider = document.getElementById('speedSlider_1');
  speedSlider.addEventListener('input', function() {
    var value = speedSlider.value;
    Manual.sendValue['PW'] = value;
    requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
    console.log("New speed value2: " + value);
  });
};

Manual.setSpeed = function(value) {
  Manual.sendValue['PW'] = value;
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
};

Manual.setSpeedValue = function (data) {
  var value = parseInt((Manual.SpeedValue * 0.2) +  (data['MS'][0] * 0.9))
  $('.speedValue .text').html(value);
}

Manual.setSpeedScale = function (data) {
  var speedValue = data['MS'][0]
  var scale = Math.round(speedValue *(21 / 30))
  $('.scale_item').css({'background': "white"})
  for (var i = 0; i < scale; i++) {
    $('.scale_item').eq(i).css({'background': "black"})
  }
}

Manual.setUltrasonic = function (data) {
  if(Manual.ultrasonicFlag == 'off'){
    Manual.ultrasonicFlag = 'on';
    Manual.sendValue['US'] = ['on', 0];
    requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
  }else{
    Manual.sendValue['US'] = ['off', 0];
    requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
  }
}

Manual.setAngleListener = function() {
  var angleSlider = document.getElementById('range_ultrasonicAngle');
  angleSlider.addEventListener('input', function() {
    var value = angleSlider.value;
    Manual.sendValue['US'] = ['on', value];
    requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue));
    
    //console.log("New speed value2: " + value);
  });
};

let distanceValues = []; // Array to store distance values
const MAX_VALUES = 3; // Maximum number of values to calculate the median
const DISTANCE_RANGE = [0, 500]; // Range of valid distance values

Manual.setUltrasonicSean = function(data) {
  const angle = -parseInt(data[0]);
  let distance = parseInt(data[1]);
  const rad = angle * Math.PI / 180;
  distance = distance * 270 / 70;
  distance = Math.round(distance);

  // Store distance value in array
  distanceValues.push(distance);

  // If the number of values in the array exceeds the maximum, remove the oldest value
  if (distanceValues.length > MAX_VALUES) {
    distanceValues.shift();
  }

  // Filter out negative and NaN values from the array
  const filteredValues = distanceValues.filter(function(val) {
    return !isNaN(val) && val >= DISTANCE_RANGE[0] && val <= DISTANCE_RANGE[1];
  });

  // Sort the array in ascending order
  filteredValues.sort(function(a, b) {
    return a - b;
  });

  // Calculate the median
  let median;
  if (filteredValues.length % 2 === 0) { // array length is even
    median = (filteredValues[filteredValues.length / 2 - 1] + filteredValues[filteredValues.length / 2]) / 2;
  } else { // array length is odd
    median = filteredValues[(filteredValues.length - 1) / 2];
  }

  // Check if median is NaN, if not, print median and angle
  if (!isNaN(median)) {
    //console.log("Median distance: " + median + ", Angle: " + angle);
    Manual.ultrasonicDist = median;
  }
};

Manual.setUltrasonicSeanDebounced = function(data) {
  // Clear the previous debounce timeout
  clearTimeout(debounceTimeout);

  // Set a new debounce timeout to delay the update
  debounceTimeout = setTimeout(() => {
    Manual.setUltrasonicSean(data);
  }, 300); // Set the debounce timeout to 300 milliseconds (adjust as needed)
};

Manual.upArrowEvent = function () {
  Manual.sendValue['RC'] = 'forward'
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
}

Manual.downArrowEvent = function () {
  Manual.sendValue['RC'] = 'backward'
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
}

Manual.leftArrowEvent = function () {
  Manual.sendValue['RC'] = 'turn_left'
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
}

Manual.rightArrowEvent = function () {
  Manual.sendValue['RC'] = 'turn_right'
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
}

Manual.stop = function () {
  Manual.sendValue['RC'] = 'rest'
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
}


/*
Manual.menuItemClick = function (reset) {
  if (arguments.length > 0) {
    $('.menu_item').off('click')
    flag_aviod = true;
    flag_follow = true;
    flag_cliff = true;
    flag_path = true;
    flag_auto = true;
    flag_ultrasonic = true;
    flag_grayScale = true;
    $('.menu_item').css({'opacity': 0.5});
    $('.menu_item_setting').css({'opacity': 1});
  }
*/  
var flag_aviod = true,flag_follow = true,flag_cliff = true,flag_path = true,flag_auto = true, flag_ultrasonic = true, flag_grayScale = true;


Manual.radarOn = function() {
  Manual.ultrasonicFlag = 'on';
  Manual.sendValue['RD'] = Manual.ultrasonicFlag;
  ////$(this).css({'opacity': 1})
  ////$('.menu_item_follow').css({'opacity': 0.5})
  ////flag_ultrasonic = false;
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
  console.log('radarOn');
  ////Manual.ultrasonicFlag = 'off';
  ////Manual.sendValue['RD'] = Manual.ultrasonicFlag;
  ////$(this).css({'opacity': 0.5})
  ////flag_ultrasonic = true;
  ////requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
}

Manual.radarOff = function() {
  Manual.ultrasonicFlag = 'off';
  Manual.sendValue['RD'] = Manual.ultrasonicFlag;
  ////$(this).css({'opacity': 0.5})
  ////flag_ultrasonic = true;
  requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))


}
/*
  $('.menu_item_grayScale').click(function() {
    if (flag_grayScale) {
      Manual.grayscaleFlag = 'on';
      Manual.sendValue['GS'] = Manual.grayscaleFlag;
      //$(this).css({'opacity': 1})
      //$('.menu_item_follow').css({'opacity': 0.5})
      flag_grayScale = false;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }else {
      Manual.grayscaleFlag = 'off';
      Manual.sendValue['GS'] = Manual.grayscaleFlag;
      $(this).css({'opacity': 0.5})
      flag_grayScale = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }

  })
  $('.menu_item_aviod').click(function() {
    if (flag_aviod) {
      Manual.aviodFlag = 'on';
      Manual.followFlag = 'off'
      Manual.sendValue['OA'] = Manual.aviodFlag;
      Manual.sendValue['RD'] = 'on'
      $(this).css({'opacity': 1})
      $('.menu_item_follow').css({'opacity': 0.5})
      flag_aviod = false;
      flag_follow = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }else {
      Manual.aviodFlag = 'off'
      Manual.followFlag = 'off'
      Manual.sendValue['OA'] = Manual.aviodFlag;
      Manual.sendValue['RD'] = Manual.ultrasonicFlag;
      $(this).css({'opacity': 0.5})
      flag_aviod = true;
      flag_follow = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }

  })

  $('.menu_item_follow').click(function() {
    if (flag_follow) {
      Manual.aviodFlag = 'off';
      Manual.followFlag = 'on'
      Manual.sendValue['OF'] = Manual.followFlag;
      Manual.sendValue['RD'] = 'on'
      $('.menu_item_aviod').css({'opacity': 0.5})
      $(this).css({'opacity': 1})
      flag_follow = false;
      flag_aviod = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }else {
      Manual.aviodFlag = 'off'
      Manual.followFlag = 'off'
      Manual.sendValue['OF'] = Manual.followFlag;
      Manual.sendValue['RD'] = Manual.ultrasonicFlag;
      $(this).css({'opacity': 0.5})
      flag_follow = true;
      flag_aviod = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }
  })
  $('.menu_item_cliff').click(function() {
    if (flag_cliff) {
      Manual.cliffFlag = 'on';
      Manual.sendValue['CD'] = ['on', Setting.grayscale.cliffReference]
      Manual.sendValue['GS'] = 'on';
      $(this).css({'opacity': 1})
      flag_cliff = false;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }else {
      Manual.cliffFlag = 'off';
      Manual.sendValue['CD'] = ['off', Setting.grayscale.cliffReference]
      Manual.sendValue['GS'] = Manual.grayscaleFlag;
      $(this).css({'opacity': 0.5})
      flag_cliff = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }
  })
  $('.menu_item_path').click(function() {
    if (flag_path) {
      Manual.sendValue['TL'] = ['on', Setting.grayscale.lineReference]
      Manual.sendValue['GS'] = 'on';
      $(this).css({'opacity': 1})
      flag_path = false;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }else {
      Manual.sendValue['TL'] = ['off', Setting.grayscale.lineReference]
      Manual.sendValue['GS'] = Manual.grayscaleFlag;
      $(this).css({'opacity': 0.5})
      flag_path = true;
      requireWebsocket.reqWs.send(JSON.stringify(Manual.sendValue))
    }
  })
  $('.menu_item_setting').click(function() {
    Main.renderPage('setting');
    console.log('dfsd')
  })
}*/

Manual.setGrayscaleColor = function (data) {
  for (var i = 0; i < data['GS'].length; i++) {
    if (data['GS'][i] < Setting.grayscale.cliffReference) {
      $('.line_of_inspection_item_danger').eq(i).show().css({'background': "red"}).find('img').show();
    }else if (data['GS'][i] < Setting.grayscale.lineReference){
      $('.line_of_inspection_item_danger').eq(i).show().css({'background': "black"}).find('img').hide();
    }else {
      $('.line_of_inspection_item_danger').eq(i).show().css({'background': "none"}).find('img').hide();
    }
  }
}

Manual.mileage = function (data) {
  if (Manual.mileageObj['last'] != undefined) {
    Manual.mileageObj['first'] = Manual.mileageObj['last'];
  }
  Manual.mileageObj['last'] = data;
  var timeFirst = parseFloat(Manual.mileageObj['first'][1]);
  var timeLast = parseFloat(Manual.mileageObj['last'][1]);
  var speedFirst = parseFloat(Manual.mileageObj['first'][0]);
  var speedLast = parseFloat(Manual.mileageObj['last'][0]);
  if (Manual.mileageObj['first'] != undefined) {
    Manual.mileageValue += ((speedFirst + speedLast) / 2) * (timeLast - timeFirst)
    $('.mileage>span').html(`${Math.round(Manual.mileageValue)}cm`)
  }
}
