/**
 * Map Renderer for Chunked Streaming
 */

export class ChunkedMapRenderer {
    constructor(map) {
        this.map = map;
        this.deckOverlay = null;
        this.dataManager = null;
        this.currentLayers = [];
        this.renderOptions = {
            showTracks: true,
            showVessels: true,
            colorBySpeed: true,
            trackOpacity: 60
        };
    }

    /**
     * 초기화
     */
    initialize() {
        this.deckOverlay = new deck.MapboxOverlay({
            interleaved: true,
            layers: []
        });
        
        this.map.addControl(this.deckOverlay);
        this.map.addControl(new maplibregl.NavigationControl());
    }

    /**
     * 데이터 매니저 설정
     */
    setDataManager(dataManager) {
        this.dataManager = dataManager;
    }

    /**
     * 렌더링 옵션 설정
     */
    setRenderOptions(options) {
        this.renderOptions = { ...this.renderOptions, ...options };
    }

    /**
     * 레이어 업데이트
     */
    updateLayers(currentTime = null) {
        if (!this.dataManager) return;
        
        const layers = [];
        
        // 디버그 로그 제거
        
        // 궤적 레이어
        if (this.renderOptions.showTracks) {
            const pathLayer = this.createPathLayer();
            if (pathLayer) layers.push(pathLayer);
        }
        
        // 선박 아이콘 레이어
        if (this.renderOptions.showVessels && currentTime) {
            const vesselLayer = this.createVesselLayer(currentTime);
            if (vesselLayer) layers.push(vesselLayer);
        }
        
        this.currentLayers = layers;
        this.deckOverlay.setProps({ layers });
    }

    /**
     * 궤적 레이어 생성
     */
    createPathLayer() {
        const pathData = [];
        const opacity = this.renderOptions.trackOpacity / 100;
        const colorBySpeed = this.renderOptions.colorBySpeed;
        
        let debugCount = 0;
        this.dataManager.getVesselChunks().forEach(vessel => {
            // 캐시된 경로가 없으면 생성
            if (!vessel.cachedPath) {
                vessel.cachedPath = this.dataManager.createVesselPath(vessel);
            }
            
            if (vessel.cachedPath.geometry.length > 1) {
                const timestamps = vessel.cachedPath.timestamps;
                
                // 디버그 로그 제거 (필요시 console.debug 사용)
                debugCount++;
                
                // 시간 정보 처리
                const { startTime, endTime } = this.processTimestamps(timestamps, vessel);
                
                pathData.push({
                    path: vessel.cachedPath.geometry,
                    color: colorBySpeed ? this.getSpeedColor(vessel.avgSpeed) : [0, 255, 0],
                    width: 2,
                    vesselId: `${vessel.sigSrcCd}_${vessel.targetId}`,
                    avgSpeed: vessel.avgSpeed,
                    distance: vessel.totalDistance,
                    startTime: startTime,
                    endTime: endTime
                });
            }
        });
        
        if (pathData.length === 0) return null;
        
        return new deck.PathLayer({
            id: 'vessel-tracks',
            data: pathData,
            pickable: true,
            widthScale: 1,
            widthMinPixels: 1,
            widthMaxPixels: 3,
            getPath: d => d.path,
            getColor: d => [...d.color, opacity * 255],
            getWidth: d => d.width,
            onHover: this.showTooltip.bind(this)
        });
    }

    /**
     * 선박 아이콘 레이어 생성
     */
    createVesselLayer(currentTime) {
        const vesselPositions = this.dataManager.getVesselPositionsAtTime(currentTime);
        
        if (vesselPositions.length === 0) return null;
        
        return new deck.ScatterplotLayer({
            id: 'vessel-icons',
            data: vesselPositions,
            pickable: true,
            opacity: 0.8,
            stroked: true,
            filled: true,
            radiusScale: 1,
            radiusMinPixels: 3,
            radiusMaxPixels: 8,
            getPosition: d => d.position,
            getFillColor: [255, 0, 0],
            getLineColor: [255, 255, 255],
            getRadius: 5,
            onHover: this.showVesselTooltip.bind(this)
        });
    }

    /**
     * 타임스탬프 처리
     */
    processTimestamps(timestamps, vessel) {
        let startTime = null, endTime = null;
        
        // 첫 번째 timestamp 처리
        if (timestamps && timestamps.length > 0 && timestamps[0]) {
            const firstTs = String(timestamps[0]);
            if (firstTs.match(/^\d{10,}$/)) {
                startTime = new Date(parseInt(firstTs) * 1000);
            } else if (firstTs.includes('-') || firstTs.includes('T')) {
                startTime = new Date(firstTs);
            }
        }
        
        // 마지막 timestamp 처리
        if (timestamps && timestamps.length > 0 && timestamps[timestamps.length - 1]) {
            const lastTs = String(timestamps[timestamps.length - 1]);
            if (lastTs.match(/^\d{10,}$/)) {
                const utcTime = parseInt(lastTs) - (9 * 60 * 60); // -9시간 보정
                endTime = new Date(utcTime * 1000);
            } else if (lastTs.includes('-') || lastTs.includes('T')) {
                endTime = new Date(lastTs);
            }
        }
        
        // 유효성 검사
        if (!startTime || isNaN(startTime.getTime())) {
            console.warn(`Invalid startTime for vessel ${vessel.sigSrcCd}_${vessel.targetId}`);
            startTime = new Date();
        }
        if (!endTime || isNaN(endTime.getTime())) {
            console.warn(`Invalid endTime for vessel ${vessel.sigSrcCd}_${vessel.targetId}`);
            endTime = new Date();
        }
        
        return { startTime, endTime };
    }

    /**
     * 속도별 색상 반환
     */
    getSpeedColor(speed) {
        if (speed < 5) return [30, 144, 255];  // 0-5 knots: 파란색
        if (speed < 10) return [0, 255, 0];    // 5-10 knots: 초록색
        if (speed < 15) return [255, 255, 0];  // 10-15 knots: 노란색
        if (speed < 20) return [255, 140, 0];  // 15-20 knots: 주황색
        return [255, 0, 0];                    // 20+ knots: 빨간색
    }

    /**
     * 선박 속도별 색상 반환
     */
    getVesselColor(speed) {
        if (speed < 1) return [255, 0, 0];      // 정지: 빨간색
        if (speed < 5) return [255, 255, 0];    // 저속: 노란색
        return [0, 255, 0];                     // 이동중: 초록색
    }

    /**
     * 궤적 툴팁 표시
     */
    showTooltip(info) {
        const tooltip = document.getElementById('vesselTooltip');
        if (!tooltip) return;
        
        if (info.object) {
            const startDate = info.object.startTime instanceof Date ? 
                info.object.startTime : new Date(info.object.startTime);
            const endDate = info.object.endTime instanceof Date ? 
                info.object.endTime : new Date(info.object.endTime);
            
            tooltip.innerHTML = `
                <strong>선박 ID:</strong> ${info.object.vesselId}<br>
                <strong>평균 속도:</strong> ${info.object.avgSpeed.toFixed(1)} knots<br>
                <strong>이동 거리:</strong> ${info.object.distance.toFixed(1)} nm<br>
                <strong>시작 시간:</strong> ${startDate.toLocaleString('ko-KR')}<br>
                <strong>종료 시간:</strong> ${endDate.toLocaleString('ko-KR')}
            `;
            tooltip.style.left = info.x + 10 + 'px';
            tooltip.style.top = info.y + 10 + 'px';
            tooltip.style.display = 'block';
        } else {
            tooltip.style.display = 'none';
        }
    }

    /**
     * 선박 아이콘 툴팁 표시
     */
    showVesselTooltip(info) {
        const tooltip = document.getElementById('vesselTooltip');
        if (!tooltip) return;
        
        if (info.object) {
            tooltip.innerHTML = `
                <strong>선박 ID:</strong> ${info.object.vesselId}<br>
                <strong>현재 속도:</strong> ${info.object.speed.toFixed(1)} knots<br>
                <strong>위치:</strong> ${info.object.position[1].toFixed(4)}°N, ${info.object.position[0].toFixed(4)}°E
            `;
            tooltip.style.left = info.x + 10 + 'px';
            tooltip.style.top = info.y + 10 + 'px';
            tooltip.style.display = 'block';
        } else {
            tooltip.style.display = 'none';
        }
    }

    /**
     * 맵 범위 조정
     */
    fitMapBounds() {
        if (!this.dataManager) return;
        
        const bounds = new maplibregl.LngLatBounds();
        let hasPoints = false;
        
        this.dataManager.getVesselChunks().forEach(vessel => {
            if (!vessel.cachedPath) {
                vessel.cachedPath = this.dataManager.createVesselPath(vessel);
            }
            vessel.cachedPath.geometry.forEach(point => {
                bounds.extend(point);
                hasPoints = true;
            });
        });
        
        if (hasPoints) {
            this.map.fitBounds(bounds, { padding: 50 });
        }
    }

    /**
     * 레이어 초기화
     */
    clearLayers() {
        this.currentLayers = [];
        this.deckOverlay?.setProps({ layers: [] });
    }

    // Getters
    getRenderOptions() {
        return this.renderOptions;
    }

    getCurrentLayers() {
        return this.currentLayers;
    }
}