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

    <div class="content-cloak">
        {{ macros.m_button_group([['reset_btn', '초기화'], ['delete_completed_btn', '완료 목록 삭제'], ['go_ffmpeg_btn', 'Go FFMPEG']]) }}
    </div>
    <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">
        const package_name = "{{arg['package_name'] }}";
        const sub = "{{arg['sub'] }}";

        function on_start(silent = false) {
            $.ajax({
                url: '/' + package_name + '/ajax/' + sub + '/entity_list',
                type: "POST",
                cache: false,
                data: {},
                dataType: "json",
                global: !silent,
                success: function (data) {
                    // entity_list 응답을 처리
                    current_data = data;
                    
                    // 목록 개수가 변했거나 데이터가 없을 때만 전체 갱신 (반짝임 방지)
                    const list_body = $("#list");
                    if (data.length == 0) {
                        list_body.html("<tr><td colspan='11'><h4>작업이 없습니다.</h4><td><tr>");
                    } else if (list_body.children().length !== data.length * 2) { // make_item이 행 2개를 생성하므로
                        str = ''
                        for (i in data) {
                            str += make_item(data[i]);
                        }
                        list_body.html(str);
                    } else {
                        // 개수가 같으면 각 항목의 상태만 보강 업데이트
                        for (i in data) {
                            status_html(data[i]);
                        }
                    }
                }
            });
        }

        $(document).ready(function () {
            const socket_url = window.location.protocol + "//" + document.domain + ":" + location.port + "/anime_downloader/anilife/queue";
            console.log("Connecting to socket:", socket_url);
            const socket = io.connect(socket_url);

            socket.on('connect', function() {
                console.log('Socket connected to anilife queue!');
            });
            
            // 모든 이벤트 모니터링 (디버깅용)
            socket.onAny((event, ...args) => {
                console.log(`[Socket event: ${event}]`, args);
            });

            socket.on('start', function (data) {
                on_start();
            });
            
            socket.on('list_refresh', function (data) {
                on_start()
            });

            // 3초마다 자동 새로고침 폴백 (인디케이터 없이 조용히)
            setInterval(function() {
                on_start(true);
            }, 3000);

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

            socket.on('on_start', function (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('last', function (data) {
                status_html(data);
                button_html(data);
            });

            globalSendCommand('list', null, null, null, function (data) {
                current_data = data;
                $("#list").html('');
                console.log(data)
                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);
            });


        });


        $("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';
            document.getElementById("status_" + data.idx).innerHTML = data.status_kor;
            document.getElementById("current_pf_count_" + data.idx).innerHTML = data.current_pf_count;
            document.getElementById("current_speed_" + data.idx).innerHTML = data.current_speed;
            document.getElementById("download_time_" + data.idx).innerHTML = data.download_time;
            document.getElementById("detail_" + data.idx).innerHTML = get_detail(data);
        }

        $("body").on('click', '#reset_btn', function (e) {
            e.preventDefault();
            entity_id = $(this).data('id')
            send_data = {'command': 'reset', 'entity_id': -1}
            queue_command(send_data)
        });

        function queue_command(data) {
            $.ajax({
                url: '/' + package_name + '/ajax/' + sub + '/queue_command',
                type: "POST",
                cache: false,
                data: data,
                dataType: "json",
                success: function (ret) {
                    if (ret.ret == 'notify') {
                        $.notify('<strong>' + ret.log + '</strong>', {type: 'warning'});
                    }
                    on_start();
                }
            });
        }

    </script>
<style>
    /* 로딩 인디케이터 오버라이드 */
    #loading {
        background: rgba(15, 23, 42, 0.85) !important;
        backdrop-filter: blur(8px) !important;
    }
    
    #loading img,
    #loading svg {
        display: none !important;
        visibility: hidden !important;
        width: 0 !important;
        height: 0 !important;
    }
    
    #loading::before {
        content: '';
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 50px;
        height: 50px;
        border: 4px solid rgba(96, 165, 250, 0.2);
        border-top-color: #60a5fa;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
        z-index: 100001;
    }
    
    @keyframes spin {
        to { transform: translate(-50%, -50%) rotate(360deg); }
    }
    
    #modal_loading img,
    #modal_loading svg {
        display: none !important;
        visibility: hidden !important;
        width: 0 !important;
        height: 0 !important;
    }
    
    #modal_loading::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 40px;
        height: 40px;
        border: 3px solid rgba(96, 165, 250, 0.2);
        border-top-color: #60a5fa;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }
    /* Navigation Menu Override */
    ul.nav.nav-pills.bg-light {
        background-color: rgba(30, 41, 59, 0.6) !important;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 50rem !important;
        padding: 6px !important;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2) !important;
        display: inline-flex !important;
        flex-wrap: wrap;
        justify-content: center;
        width: auto !important;
        margin-bottom: 20px;
    }

    ul.nav.nav-pills .nav-item {
        margin: 0 2px;
    }

    ul.nav.nav-pills .nav-link {
        border-radius: 50rem !important;
        padding: 8px 20px !important;
        color: #94a3b8 !important;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    ul.nav.nav-pills .nav-link:hover {
        background-color: rgba(255, 255, 255, 0.1);
        color: #fff !important;
        transform: translateY(-1px);
    }

    ul.nav.nav-pills .nav-link.active {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
        color: #fff !important;
        box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4);
    }
</style>

<style>
    /* Smooth Load Transition */
    .content-cloak, 
    #menu_module_div, 
    #menu_page_div {
        opacity: 0;
        transition: opacity 0.5s ease-out;
    }
    
    /* Staggered Delays for Natural Top-Down Flow */
    #menu_module_div.visible {
        opacity: 1;
        transition-delay: 0ms;
    }

    #menu_page_div.visible {
        opacity: 1;
        transition-delay: 150ms;
    }

    .content-cloak.visible {
        opacity: 1;
        transition-delay: 300ms;
    }
    
    /* Navigation Menu Override (Top Sub-menu) */
    ul.nav.nav-pills.bg-light {
        background-color: rgba(30, 41, 59, 0.6) !important;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 50rem !important;
        padding: 6px !important;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2) !important;
        display: inline-flex !important;
        flex-wrap: wrap;
        justify-content: center;
        width: auto !important;
        margin-bottom: 20px;
    }

    ul.nav.nav-pills .nav-item { margin: 0 2px; }
    ul.nav.nav-pills .nav-link {
        border-radius: 50rem !important;
        padding: 8px 20px !important;
        color: #94a3b8 !important;
        font-weight: 600;
        transition: all 0.3s ease;
    }
    ul.nav.nav-pills .nav-link:hover {
        background-color: rgba(255, 255, 255, 0.1);
        color: #fff !important;
        transform: translateY(-1px);
    }
    ul.nav.nav-pills .nav-link.active {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
        color: #fff !important;
        box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4);
    }
</style>

<script type="text/javascript">
$(document).ready(function(){
  // Smooth Load Trigger
  setTimeout(function() {
      $('.content-cloak, #menu_module_div, #menu_page_div').addClass('visible');
  }, 100);
});
</script>
<style>
/* Mobile Margin Fix */
@media (max-width: 768px) {
    body { overflow-x: hidden !important; padding: 0 !important; margin: 0 !important; }
    .container, .container-fluid, .row, form, #program_list, #program_auto_form, #episode_list, .queue-container, #yommi_wrapper, #main_container {
        width: 100% !important; max-width: 100% !important;
        padding-left: 4px !important; padding-right: 4px !important;
        margin-left: 0 !important; margin-right: 0 !important;
        box-sizing: border-box !important;
    }
    .form-group, .form-inline, [class*="col-"] {
        flex: 0 0 100% !important; max-width: 100% !important; width: 100% !important;
        padding-left: 0 !important; padding-right: 0 !important;
    }
    .row { margin-left: 0 !important; margin-right: 0 !important; }
    .card, .card.p-4, .card.p-lg-5, .card.border-light {
         width: calc(100% - 8px) !important; max-width: 100% !important;
         padding: 8px !important; margin: 4px !important;
         border-radius: 12px !important; box-sizing: border-box !important;
    }
    .badge {
        white-space: normal !important; text-align: left !important;
        line-height: 1.4 !important; height: auto !important; display: inline-block !important;
    }
}
</style>
{% endblock %}
