/**
 * Chunked Streaming Utility Functions
 */

/**
 * 날짜/시간 포맷팅
 */
export function formatDateTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

/**
 * 기본 시간 범위 설정 (현재 시간 기준)
 */
export function getDefaultTimeRange() {
    const now = new Date();
    const adjusted = new Date(now.getTime() - 15 * 60 * 1000); // 15분 전
    const sixHoursAgo = new Date(adjusted.getTime() - 6 * 60 * 60 * 1000);
    
    return {
        startTime: formatDateTime(sixHoursAgo),
        endTime: formatDateTime(adjusted)
    };
}

/**
 * 지정된 시간 전의 시간 범위 생성
 */
export function createTimeRange(hours) {
    const now = new Date();
    const adjusted = new Date(now.getTime() - 15 * 60 * 1000);
    const start = new Date(adjusted.getTime() - hours * 60 * 60 * 1000);
    
    return {
        startTime: formatDateTime(start),
        endTime: formatDateTime(adjusted)
    };
}

/**
 * 맵 뷰포트 정보 추출
 */
export function getMapViewport(map) {
    const bounds = map.getBounds();
    const zoom = Math.floor(map.getZoom());
    
    return {
        viewport: {
            minLon: bounds.getWest(),
            maxLon: bounds.getEast(),
            minLat: bounds.getSouth(),
            maxLat: bounds.getNorth()
        },
        zoom
    };
}

/**
 * 뷰포트 정보를 입력 필드에 업데이트
 */
export function updateViewportDisplay(map) {
    const { viewport, zoom } = getMapViewport(map);
    
    const elements = {
        currentZoom: document.getElementById('currentZoom'),
        minLon: document.getElementById('minLon'),
        maxLon: document.getElementById('maxLon'),
        minLat: document.getElementById('minLat'),
        maxLat: document.getElementById('maxLat')
    };
    
    if (elements.currentZoom) {
        elements.currentZoom.textContent = `Zoom: ${zoom}`;
    }
    
    if (elements.minLon) elements.minLon.value = viewport.minLon.toFixed(4);
    if (elements.maxLon) elements.maxLon.value = viewport.maxLon.toFixed(4);
    if (elements.minLat) elements.minLat.value = viewport.minLat.toFixed(4);
    if (elements.maxLat) elements.maxLat.value = viewport.maxLat.toFixed(4);
}

/**
 * 로그 메시지 추가
 */
export function addLog(message, type = 'info') {
    const logContainer = document.getElementById('logContainer');
    if (!logContainer) return;
    
    const entry = document.createElement('div');
    entry.className = `log-entry log-${type}`;
    entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
    
    logContainer.appendChild(entry);
    logContainer.scrollTop = logContainer.scrollHeight;
    
    // 로그 개수 제한 (50개)
    if (logContainer.children.length > 50) {
        logContainer.removeChild(logContainer.firstChild);
    }
}

/**
 * 로그 초기화
 */
export function clearLog() {
    const logContainer = document.getElementById('logContainer');
    if (logContainer) {
        logContainer.innerHTML = '';
    }
}

/**
 * UI 요소 표시/숨김
 */
export function toggleDisplay(elementId, show) {
    const element = document.getElementById(elementId);
    if (element) {
        element.style.display = show ? 'block' : 'none';
    }
}

/**
 * 버튼 상태 업데이트
 */
export function updateButtonState(buttonId, enabled, text = null) {
    const button = document.getElementById(buttonId);
    if (button) {
        button.disabled = !enabled;
        if (text) {
            button.innerHTML = text;
        }
    }
}

/**
 * 진행률 바 업데이트
 */
export function updateProgressBar(percentage) {
    const progressBar = document.getElementById('progressBar');
    const progressContainer = document.getElementById('progressContainer');
    
    if (progressBar) {
        progressBar.style.width = percentage + '%';
        progressBar.textContent = Math.round(percentage) + '%';
    }
    
    if (progressContainer) {
        progressContainer.style.display = percentage > 0 ? 'block' : 'none';
    }
}

/**
 * 애니메이션 속도 버튼 업데이트
 */
export function updateSpeedButtons(currentSpeed) {
    document.querySelectorAll('.btn-speed').forEach(btn => {
        const speed = parseFloat(btn.textContent.replace('x', ''));
        if (speed === currentSpeed) {
            btn.classList.remove('btn-outline-secondary');
            btn.classList.add('btn-secondary');
        } else {
            btn.classList.remove('btn-secondary');
            btn.classList.add('btn-outline-secondary');
        }
    });
}

/**
 * 타임라인 UI 업데이트
 */
export function updateTimelineUI(timelineData) {
    const elements = {
        timeSlider: document.getElementById('timeSlider'),
        currentDateDisplay: document.getElementById('currentDateDisplay'),
        currentTimeDisplay: document.getElementById('currentTimeDisplay'),
        startTimeDisplay: document.getElementById('startTimeDisplay'),
        endTimeDisplay: document.getElementById('endTimeDisplay')
    };
    
    if (elements.timeSlider) {
        elements.timeSlider.value = timelineData.progress;
    }
    
    if (elements.currentDateDisplay) {
        elements.currentDateDisplay.textContent = timelineData.currentDate;
    }
    
    if (elements.currentTimeDisplay) {
        elements.currentTimeDisplay.textContent = timelineData.currentTime;
    }
    
    if (elements.startTimeDisplay) {
        elements.startTimeDisplay.textContent = timelineData.startTime;
    }
    
    if (elements.endTimeDisplay) {
        elements.endTimeDisplay.textContent = timelineData.endTime;
    }
}

/**
 * 통계 정보 업데이트
 */
export function updateStatistics(stats) {
    const elements = {
        chunksReceived: document.getElementById('chunksReceived'),
        vesselCount: document.getElementById('vesselCount'),
        pointCount: document.getElementById('pointCount'),
        dataSize: document.getElementById('dataSize'),
        processTime: document.getElementById('processTime')
    };
    
    if (elements.chunksReceived && stats.chunksReceived !== undefined) {
        elements.chunksReceived.textContent = stats.chunksReceived;
    }
    
    if (elements.vesselCount && stats.vesselCount !== undefined) {
        elements.vesselCount.textContent = stats.vesselCount;
    }
    
    if (elements.pointCount && stats.pointCount !== undefined) {
        elements.pointCount.textContent = stats.pointCount.toLocaleString();
    }
    
    if (elements.dataSize && stats.dataSize !== undefined) {
        elements.dataSize.textContent = stats.dataSize.toFixed(1);
    }
    
    if (elements.processTime && stats.processTime !== undefined) {
        elements.processTime.textContent = stats.processTime;
    }
}

/**
 * 렌더링 옵션 읽기
 */
export function getRenderOptions() {
    return {
        showTracks: document.getElementById('showTracks')?.checked ?? true,
        showVessels: document.getElementById('showVessels')?.checked ?? true,
        colorBySpeed: document.getElementById('colorBySpeed')?.checked ?? true,
        trackOpacity: parseInt(document.getElementById('trackOpacity')?.value ?? 60)
    };
}

/**
 * DOM 요소 안전 접근
 */
export function safeGetElement(id) {
    const element = document.getElementById(id);
    if (!element) {
        console.warn(`Element with id '${id}' not found`);
    }
    return element;
}

/**
 * 안전한 이벤트 리스너 등록
 */
export function safeAddEventListener(id, event, handler) {
    const element = safeGetElement(id);
    if (element) {
        element.addEventListener(event, handler);
        return true;
    }
    return false;
}

/**
 * 쿼리 파라미터 검증
 */
export function validateQueryParams(startTime, endTime) {
    const errors = [];
    
    if (!startTime || !endTime) {
        errors.push('시작 시간과 종료 시간을 모두 입력하세요');
    }
    
    const start = new Date(startTime);
    const end = new Date(endTime);
    
    if (start >= end) {
        errors.push('종료 시간은 시작 시간보다 이후여야 합니다');
    }
    
    const maxRange = 7 * 24 * 60 * 60 * 1000; // 7일
    if (end - start > maxRange) {
        errors.push('최대 조회 기간은 7일입니다');
    }
    
    return {
        valid: errors.length === 0,
        errors
    };
}

/**
 * 에러 메시지 표시
 */
export function showError(message) {
    addLog(`에러: ${message}`, 'error');
    // 추가적인 에러 표시 로직 (예: 모달, 토스트 등)
}

/**
 * 성공 메시지 표시
 */
export function showSuccess(message) {
    addLog(message, 'success');
}