/**
 * Chunked Data Manager - 선박 데이터 관리
 */

export class ChunkedDataManager {
    constructor() {
        this.vesselChunks = new Map();
        this.vesselTimeIndex = new Map();
        this.chunksReceived = 0;
        this.totalDataSize = 0;
        this.totalPoints = 0;
        this.startTime = null;
    }

    /**
     * 초기화
     */
    reset() {
        this.vesselChunks.clear();
        this.vesselTimeIndex.clear();
        this.chunksReceived = 0;
        this.totalDataSize = 0;
        this.totalPoints = 0;
        this.startTime = null;
    }

    /**
     * 청크 데이터 처리
     */
    processChunk(message) {
        const parseStart = performance.now();
        const chunk = JSON.parse(message.body);
        
        this.chunksReceived++;
        this.totalDataSize += message.body.length / 1024;

        // 첫 번째와 마지막 청크만 로그
        if (this.chunksReceived === 1 || chunk.isLast) {
            console.log(`[CHUNK ${this.chunksReceived}] Received:`, {
                tracksCount: chunk.compactTracks ? chunk.compactTracks.length : 0,
                isLast: chunk.isLast
            });
        }

        if (chunk.compactTracks) {
            chunk.compactTracks.forEach((track, idx) => {
                this.processTrack(track, idx);
            });
        }

        const parseTime = performance.now() - parseStart;
        
        return {
            chunk,
            parseTime,
            stats: chunk.stats || {}
        };
    }

    /**
     * 개별 트랙 처리
     */
    processTrack(track, idx) {
        const vesselId = track.vesselId;
        
        // 디버그 모드일 때만 첫 번째 트랙 로그
        if (idx === 0 && this.chunksReceived === 1) {
            console.log(`[FIRST_TRACK] ${vesselId}:`, {
                timestampsLength: track.timestamps ? track.timestamps.length : 0,
                geometryLength: track.geometry ? track.geometry.length : 0
            });
        }
        
        // 청크 단위로 저장 (병합하지 않음)
        if (!this.vesselChunks.has(vesselId)) {
            this.vesselChunks.set(vesselId, {
                sigSrcCd: track.sigSrcCd,
                targetId: track.targetId,
                chunks: [],
                cachedPath: null,
                totalDistance: 0,
                avgSpeed: 0,
                maxSpeed: 0
            });
        }
        
        const vessel = this.vesselChunks.get(vesselId);
        
        // 청크 추가
        vessel.chunks.push({
            geometry: track.geometry,
            timestamps: track.timestamps,
            speeds: track.speeds,
            pointCount: track.geometry.length
        });
        
        // 캐시 무효화
        vessel.cachedPath = null;
        
        // 통계 업데이트
        vessel.totalDistance += track.totalDistance || 0;
        vessel.maxSpeed = Math.max(vessel.maxSpeed, track.maxSpeed || 0);
        vessel.avgSpeed = track.avgSpeed || 0;
        
        this.totalPoints += track.geometry.length;
    }

    /**
     * 선박 경로 생성 (렌더링 시점에만)
     */
    createVesselPath(vessel) {
        // flatMap으로 가상 병합 (메모리 복사 없음)
        const path = {
            geometry: vessel.chunks.flatMap(c => c.geometry),
            timestamps: vessel.chunks.flatMap(c => c.timestamps),
            speeds: vessel.chunks.flatMap(c => c.speeds)
        };
        
        // 필요시에만 디버그 로그 (개발 환경에서만)
        // console.debug(`Path created for ${vessel.sigSrcCd}_${vessel.targetId}`);
        
        return path;
    }

    /**
     * 특정 시간의 선박 위치 계산
     */
    getVesselPositionsAtTime(targetTime) {
        const positions = [];
        
        this.vesselChunks.forEach(vessel => {
            const pos = this.interpolatePosition(vessel, targetTime);
            if (pos) {
                positions.push({
                    vesselId: `${vessel.sigSrcCd}_${vessel.targetId}`,
                    position: [pos.lon, pos.lat],
                    speed: pos.speed || vessel.avgSpeed
                });
            }
        });
        
        return positions;
    }

    /**
     * 위치 보간 (청크 기반)
     */
    interpolatePosition(vessel, targetTime) {
        // 캐시된 경로가 없으면 생성
        if (!vessel.cachedPath) {
            vessel.cachedPath = this.createVesselPath(vessel);
        }
        
        const timestamps = vessel.cachedPath.timestamps;
        if (!timestamps || timestamps.length === 0) return null;
        
        // Unix timestamp(초) 문자열을 밀리초로 변환 (KST 보정)
        const times = timestamps.map(t => {
            if (typeof t === 'string' && t.match(/^\d{10,}$/)) {
                // Unix timestamp - KST로 저장된 값이므로 -9시간 보정
                const utcTime = parseInt(t) - (9 * 60 * 60);
                return utcTime * 1000;
            } else {
                return new Date(t).getTime();
            }
        });
        
        const firstTime = times[0];
        const lastTime = times[times.length - 1];
        
        if (targetTime < firstTime || targetTime > lastTime) return null;
        
        // 이진 탐색으로 인덱스 찾기
        let left = 0;
        let right = times.length - 1;
        
        while (left < right - 1) {
            const mid = Math.floor((left + right) / 2);
            if (times[mid] <= targetTime) {
                left = mid;
            } else {
                right = mid;
            }
        }
        
        if (left === right) {
            return {
                lon: vessel.cachedPath.geometry[left][0],
                lat: vessel.cachedPath.geometry[left][1],
                speed: vessel.cachedPath.speeds[left]
            };
        }
        
        // 선형 보간
        const t1 = times[left];
        const t2 = times[right];
        const ratio = (targetTime - t1) / (t2 - t1);
        
        return {
            lon: vessel.cachedPath.geometry[left][0] + (vessel.cachedPath.geometry[right][0] - vessel.cachedPath.geometry[left][0]) * ratio,
            lat: vessel.cachedPath.geometry[left][1] + (vessel.cachedPath.geometry[right][1] - vessel.cachedPath.geometry[left][1]) * ratio,
            speed: vessel.cachedPath.speeds[left] + (vessel.cachedPath.speeds[right] - vessel.cachedPath.speeds[left]) * ratio
        };
    }

    /**
     * 시간 인덱스 구축 (필요시)
     */
    buildTimeIndex() {
        this.vesselTimeIndex.clear();
        
        this.vesselChunks.forEach((vessel, vesselId) => {
            if (!vessel.cachedPath) {
                vessel.cachedPath = this.createVesselPath(vessel);
            }
            
            vessel.cachedPath.timestamps.forEach((timestamp, idx) => {
                const time = new Date(timestamp).getTime();
                const minute = Math.floor(time / 60000) * 60000; // 분 단위
                
                if (!this.vesselTimeIndex.has(minute)) {
                    this.vesselTimeIndex.set(minute, []);
                }
                
                this.vesselTimeIndex.get(minute).push({
                    vesselId,
                    idx,
                    time
                });
            });
        });
    }

    // Getters
    getVesselChunks() {
        return this.vesselChunks;
    }

    getStatistics() {
        return {
            chunksReceived: this.chunksReceived,
            vesselCount: this.vesselChunks.size,
            pointCount: this.totalPoints,
            dataSize: this.totalDataSize
        };
    }

    hasData() {
        return this.vesselChunks.size > 0;
    }
}