{% extends "base.html" %}
{% block content %}


<table id="result_table" class="table table-sm tableRowHover">
  <thead class="thead-dark">
    <tr>
      <th style="width:5%; text-align:center;">IDX</th>
      <th style="width:8%; text-align:center;">Plugin</th>
      <th style="width:10%; text-align:center;">시작시간</th>
      <th style="width:20%; text-align:center;">파일명</th>
      <th style="width:8%; text-align:center;">상태</th>
      <th style="width:15%; text-align:center;">진행률</th>
      <th style="width:5%; text-align:center;">길이</th>
      <th style="width:5%; text-align:center;">PF</th>
      <th style="width:8%; text-align:center;">배속</th>
      <th style="width:8%; text-align:center;">진행시간</th>
      <th style="width:8%; text-align:center;">Action</th>
    </tr>
  </thead>
  <tbody id="list"></tbody>
</table>

<script type="text/javascript">

$(document).ready(function(){
  console.log('Queue page loaded, connecting to sockets...');
  
  var protocol = location.protocol;
  var socketUrl = protocol + "//" + document.domain + ":" + location.port;
  
  // Queue 페이지 전용 namespace 연결
  var queueSocket = null;
  try {
    queueSocket = io.connect(socketUrl + '/anime_downloader/linkkf/queue');
    console.log('Queue socket connecting to:', socketUrl + '/anime_downloader/linkkf/queue');
  } catch (e) {
    console.error('Queue socket connect error:', e);
  }
  
  // /framework namespace 연결 (FlaskFarm 기본 알림용)
  var frameworkSocket = null;
  try {
    frameworkSocket = io.connect(socketUrl + '/framework');
    console.log('Framework socket connecting to:', socketUrl + '/framework');
    
    frameworkSocket.on('connect', function() {
      console.log('Framework socket connected!');
    });
    
    // linkkf_status 이벤트로 다운로드 상태 업데이트 수신
    frameworkSocket.on('linkkf_status', function(data) {
      status_html(data);
    });
  } catch (e) {
    console.error('Framework socket connect error:', e);
  }
  
  // Queue socket으로 직접 이벤트 받기
  var socket = queueSocket;
  
  if (socket) {
    socket.on('connect', function() {
      console.log('Socket connected! socket.id:', socket.id);
    });
  
    socket.on('disconnect', function() {
      console.log('Socket disconnected!');
    });
  
    socket.on('connect_error', function(err) {
      console.log('Socket connect error:', err);
    });
  
    // 모든 이벤트 수신 테스트
    socket.onAny(function(event, ...args) {
      console.log('Socket event received:', event, args);
    });

    socket.on('on_start', function(data){
      console.log('on_start received:', data);
      document.getElementById("log").innerHTML += data.data;
      document.getElementById("log").scrollTop = document.getElementById("log").scrollHeight;
      document.getElementById("log").style.visibility = 'visible';
      $('#loading').hide();
    });

    socket.on('add', function(data){
      str = make_item(data);
      if (current_data == null || current_data.length == 0) {
        current_data = Array();
        $("#list").html(str);
      } else {
        $("#list").html($("#list").html() + str);
      }
      current_data.push(data);
    });

    socket.on('status_change', function(data) {
      button_html(data);
    });

    socket.on('status', function(data){
      console.log('status received:', data);
      status_html(data);
    });

    socket.on('last', function(data){
      status_html(data);
      button_html(data);
    });
  }

  var refreshIntervalId = null;
  
  // 로딩 인디케이터 없이 조용히 목록 가져오기
  function silentFetchList(callback) {
    $.ajax({
      url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command',
      type: 'POST',
      cache: false,
      global: false,  // 로딩 인디케이터 표시 안함
      data: {command: 'list'},
      dataType: 'json',
      success: function(data) {
        if (callback) callback(data);
      },
      error: function(xhr, status, error) {
        // 에러 무시
      }
    });
  }
  
  // 자동 새로고침 (로딩 인디케이터 없음)
  function autoRefreshList() {
    silentFetchList(function(data) {
      // 새 아이템이 추가되었는지 확인
      if (!current_data || data.length !== current_data.length) {
        current_data = data;
        $("#list").html('');
        console.log('Refreshed list:', data.length, 'items');
        if (data.length == 0) {
          str = "<tr><td colspan='10'><h4>작업이 없습니다.</h4><td><tr>";
        } else {
          str = ''
          for(i in data) {
            str += make_item(data[i]);
          }
        }
        $("#list").html(str);
      }
      
      // 진행 중인 다운로드가 있는지 확인
      var hasActiveDownload = false;
      if (data && data.length > 0) {
        for (var j = 0; j < data.length; j++) {
          if (data[j].status_str === 'DOWNLOADING' || data[j].status_str === 'WAITING') {
            hasActiveDownload = true;
            break;
          }
        }
      }
      
      // 모든 다운로드 완료 시 자동 새로고침 중지
      if (!hasActiveDownload && refreshIntervalId) {
        console.log('All downloads completed, stopping auto-refresh');
        clearInterval(refreshIntervalId);
        refreshIntervalId = null;
      }
      
      // 활성 다운로드가 있고 새로고침이 중지된 경우 재시작
      if (hasActiveDownload && !refreshIntervalId) {
        console.log('Active downloads detected, starting auto-refresh');
        refreshIntervalId = setInterval(autoRefreshList, 3000);
      }
    });
  }
  
  // 초기 로드 (로딩 인디케이터 표시)
  globalSendCommand('list', null, null, null, function(data) {
    current_data = data;
    $("#list").html('');
    if (data.length == 0) {
      str = "<tr><td colspan='10'><h4>작업이 없습니다.</h4><td><tr>";
    } else {
      str = ''
      for(i in data) {
        str += make_item(data[i]);
      }
    }
    $("#list").html(str);
  });
  
  // 3초마다 자동 새로고침 (로딩 인디케이터 없음)
  refreshIntervalId = setInterval(autoRefreshList, 3000);
});


$("body").on('click', '#stop_btn', function(e){
  e.stopPropagation();
  e.preventDefault();
  globalSendCommand('stop', $(this).data('idx'), null, null, function(ret){
    refresh_item(ret.data);
  });
});


function refresh_item(data) {
  $('#tr1_'+data.idx).html(make_item1(data));
  $('#collapse_'+data.idx).html(make_item2(data));
}

function make_item(data) {
  str = '<tr id="tr1_'+data.idx+'" style="cursor: pointer;" data-toggle="collapse" data-target="#collapse_'+ data.idx + '" aria-expanded="true" >';
  str += make_item1(data);
  str += '</tr>';
  str += '<tr class="collapse tableRowHoverOff" style="cursor: pointer;"  id="collapse_' + data.idx + '">';
  str += make_item2(data);
  str += '</tr>';
  return str;
}

function make_item1(data) {
  //console.log(data);
  str = '';
  str += '<td scope="col" style="width:5%; text-align:center;">'+ data.idx + '</td>';
  str += '<td scope="col" style="width:8%; text-align:center;">'+ data.callback_id + '</td>';
  str += '<td scope="col" style="width:10%; text-align:center;">'+ data.start_time + '</td>';
  str += '<td scope="col" style="width:20%; text-align:center;">'+ data.filename + '</td>';
  str += '<td id="status_'+data.idx+'" scope="col" style="width:8%; text-align:center;">'+ data.status_kor + '</td>';
  var visi = 'hidden';
  if (parseInt(data.percent) > 0) {
    visi = 'visible';
  }
  str += '<td scope="col" style="width:20%; text-align:center;"><div class="progress"><div id="progress_'+data.idx+'" class="progress-bar" style="visibility: '+visi+'; width:'+data.percent+'%">'+data.percent +'%</div></div></td>';
  str += '<td scope="col" style="width:5%; text-align:center;">'+ data.duration_str + '</td>';
  str += '<td id="current_pf_count_'+data.idx+'" scope="col" style="width:5%; text-align:center;">'+ data.current_pf_count + '</td>';
  str += '<td id="current_speed_'+data.idx+'" scope="col" style="width:8%; text-align:center;">'+ data.current_speed + '</td>';
  str += '<td id="download_time_'+data.idx+'" scope="col" style="width:8%; text-align:center;">'+ data.download_time + '</td>';
  str += '<td id="button_'+data.idx+'" scope="col" style="width:8%; text-align:center;">';
  if (data.status_str == 'DOWNLOADING') {
    str += j_button('stop_btn', '중지', {'idx':data.idx}, 'danger', false, false);
  }
  str += '</td>'
  return str;
}

function make_item2(data) {
  str = '';
  str += '<td colspan="11">';
  str += '<div id="detail_'+data.idx+'">';
  str += get_detail(data);
  str += '</div>';
  str += '</td>';
  return str
}


function get_detail(data) {
  var str = j_row_info('URL', data.url);
  str += j_row_info('임시경로', data.temp_fullpath);
  str += j_row_info('저장경로', data.save_fullpath);
  str += j_row_info('진행률(current/total)', data.percent+ '% (' + data.current_duration + ' / ' + data.duration + ')');
  str += j_row_info('현재 비트레이트', data.current_bitrate);
  str += j_row_info('종료시간', data.end_time);
  str += j_row_info('허용 Packet Fail 수', data.max_pf_count);
  str += j_row_info('파일 Exist', data.exist);
  if (data.status_str == 'COMPLETED') {
    str += j_row_info('파일 크기', data.filesize_str);
    str += j_row_info('다운 속도', data.download_speed);
  }
  return str;
}

function button_html(data) {
  //console.log(data)
  str = '';
  if (data.status_str == 'DOWNLOADING') {
    str = j_button('stop_btn', '중지', {'idx':data.idx}, 'danger', false, false);
  }
  $("#button_" + data.idx).html(str);
}

function status_html(data) {
  var progress = document.getElementById("progress_" + data.idx);
  if (!progress) {
    return;
  }
  progress.style.width = data.percent+ '%';
  progress.innerHTML = data.percent+ '%';
  progress.style.visibility = 'visible';
  
  var statusEl = document.getElementById("status_" + data.idx);
  if (statusEl) statusEl.innerHTML = data.status_kor;
  
  var pfEl = document.getElementById("current_pf_count_" + data.idx);
  if (pfEl) pfEl.innerHTML = data.current_pf_count;
  
  var speedEl = document.getElementById("current_speed_" + data.idx);
  if (speedEl) speedEl.innerHTML = data.current_speed;
  
  var timeEl = document.getElementById("download_time_" + data.idx);
  if (timeEl) timeEl.innerHTML = data.download_time;
  
  var detailEl = document.getElementById("detail_" + data.idx);
  if (detailEl) detailEl.innerHTML = get_detail(data);
}

</script>
{% endblock %}
