document.addEventListener('DOMContentLoaded', function () {
  const terminateAction = document.getElementById('terminateAction');
  const finishAction = document.getElementById('finishAction');
  const exitAppButton = document.getElementById('exitAppButton');

  const stackerStartButton = document.getElementById('stackerStartButton');
  const stackerStopButton = document.getElementById('stackerStopButton');
  const upDownOnButton = document.getElementById('upDownOnButton');
  const upDownOffButton = document.getElementById('upDownOffButton');
  const leftRightOnButton = document.getElementById('leftRightOnButton');
  const leftRightOffButton = document.getElementById('leftRightOffButton');

  function logAction(message) {
    fetch('/writelog', {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain',
      },
      body: message,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to write log.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(`Log result: ${data}`);
      })
      .catch((error) => console.error('Error writing log:', error));
  }

  // 인덱스 표시 업데이트 함수
  function updateIndexDisplay() {
    fetch('/static/json/cache.json')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((data) => {
        document.getElementById('currentDataIndex').textContent =
          data.currentDataIndex + 1;
        document.getElementById('currentLayerIndex').textContent =
          data.currentLayerIndex + 1;
        console.log(data.currentDataIndex, data.currentLayerIndex);
      })
      .catch((error) => console.error('Error loading cache.json:', error));
  }

  // 페이지 로드 시 초기 인덱스 표시 업데이트
  updateIndexDisplay();

  // 일정 시간마다 인덱스 표시 업데이트
  intervalId = setInterval(updateIndexDisplay, 5000); // 5초마다 업데이트

  finishAction.addEventListener('click', function () {
    finishAction.disabled = true;
    fetch('/robot_immediately_take_book', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        immediately_take_book: 'robot_immediately_take_book',
      }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('immediately_take_book failed.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction(
          'FE : robot_immediately_take_book api sent successfully - progress.js'
        );
      })
      .catch((error) =>
        console.error('Error Sending robot finish action:', error)
      ).finally(() => {
        setTimeout(() => {
          finishAction.disabled = false;
        }, 10000);
      })
  });

  terminateAction.addEventListener('click', function () {
    fetch('/robot_finish_action', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'robot_finish_action' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send robot finish action.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        clearInterval(intervalId);
        logAction(
          'FE : robot_finish_action api sent successfully - progress.js'
        );

        window.location.href = '/';
      })
      .catch((error) =>
        console.error('Error sending robot finish action:', error)
      );
  });

  exitAppButton.addEventListener('click', function () {
    fetch('/shutdown', {
      method: 'POST',
    })
      .then((response) => response.text())
      .then((data) => {
        console.log(data);
        logAction('FE : shutdown api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error shutting down:', error));
  });

  stackerStartButton.addEventListener('click', function () {
    fetch('/stacker_start', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'stacker_start' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send stacker start.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : stacker_start api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error sending stacker start:', error));
  });

  stackerStopButton.addEventListener('click', function () {
    fetch('/stacker_stop', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'stacker_stop' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send stacker stop.');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : stacker_stop api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error sending stacker stop:', error));
  });

  upDownOnButton.addEventListener('click', function () {
    fetch('/updown_on', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'updown_on' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send updown on');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : updown_on api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error sending updown on:', error));
  });

  upDownOffButton.addEventListener('click', function () {
    fetch('/updown_off', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'updown_off' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send updown off');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : updown_off api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error sending updown off:', error));
  });

  leftRightOnButton.addEventListener('click', function () {
    fetch('/leftright_on', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'leftright_on' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send leftright on');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : leftright_on api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error sending leftright on:', error));
  });

  leftRightOffButton.addEventListener('click', function () {
    fetch('/leftright_off', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ action: 'leftright_off' }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to send leftright off');
        }
        return response.text();
      })
      .then((data) => {
        console.log(data);
        logAction('FE : leftright_off api sent successfully - progress.js');
      })
      .catch((error) => console.error('Error sending leftright off:', error));
  });
});
