/**
 * GIS 선박 관리자 컴포넌트
 */

import { parseLineStringM, formatDistance, formatSpeed, passesFilters } from '../utils/gis-utils.js';
import { TrackAPI } from '../api/gis-api.js';

export class GISVesselManager {
    constructor() {
        this.vesselList = [];
        this.selectedVessels = new Set();
        this.tracks = [];
        this.currentArea = null;
        this.filters = {
            minSpeed: 0,
            maxSpeed: 50,
            minDist: 0,
            maxDist: 200
        };
        this.sortBy = 'id';
        this.sortOrder = 'asc';
    }

    /**
     * 구역의 선박 목록 로드
     */
    async loadVesselList(type, id, timeRange) {
        this.currentArea = { type, id };
        
        try {
            const tracks = await TrackAPI.getByArea(type, id, timeRange);
            
            // 선박별로 그룹화
            const vesselMap = new Map();
            
            tracks.forEach(track => {
                const vesselId = `${track.sig_src_cd}_${track.target_id}`;
                
                if (!vesselMap.has(vesselId)) {
                    vesselMap.set(vesselId, {
                        id: vesselId,
                        sig_src_cd: track.sig_src_cd,
                        target_id: track.target_id,
                        distance: 0,
                        speeds: [],
                        tracks: [],
                        type: type,
                        area_id: id
                    });
                }
                
                const vessel = vesselMap.get(vesselId);
                vessel.distance += parseFloat(track.distance_nm) || 0;
                vessel.speeds.push(parseFloat(track.avg_speed) || 0);
                vessel.tracks.push(track);
            });
            
            // 통계 계산
            this.vesselList = Array.from(vesselMap.values()).map(vessel => ({
                ...vessel,
                avg_speed: vessel.speeds.reduce((a, b) => a + b, 0) / vessel.speeds.length,
                max_speed: Math.max(...vessel.speeds),
                track_count: vessel.tracks.length
            }));
            
            return this.vesselList;
        } catch (error) {
            console.error('Failed to load vessel list:', error);
            this.vesselList = [];
            throw error;
        }
    }

    /**
     * 선택된 선박들의 트랙 로드
     */
    async loadSelectedTracks(period) {
        this.tracks = [];
        
        if (this.selectedVessels.size === 0) {
            return this.tracks;
        }
        
        const trackPromises = [];
        
        for (const vessel of this.vesselList) {
            if (this.selectedVessels.has(vessel.id)) {
                trackPromises.push(
                    this.loadVesselTrack(vessel, period)
                );
            }
        }
        
        const results = await Promise.allSettled(trackPromises);
        
        results.forEach(result => {
            if (result.status === 'fulfilled' && result.value) {
                this.tracks.push(result.value);
            }
        });
        
        return this.tracks;
    }

    /**
     * 개별 선박 트랙 로드
     */
    async loadVesselTrack(vessel, period) {
        try {
            const tracks = await TrackAPI.getByArea(vessel.type, vessel.area_id, period);
            
            const vesselTracks = tracks.filter(t => 
                `${t.sig_src_cd}_${t.target_id}` === vessel.id
            );
            
            if (vesselTracks.length === 0) {
                return null;
            }
            
            // 트랙 포인트 병합
            const allPoints = [];
            let totalDistance = 0;
            const speeds = [];
            
            vesselTracks.forEach(track => {
                const points = parseLineStringM(track.track_geom);
                allPoints.push(...points);
                totalDistance += parseFloat(track.distance_nm) || 0;
                speeds.push(parseFloat(track.avg_speed) || 0);
            });
            
            if (allPoints.length === 0) {
                return null;
            }
            
            return {
                path: allPoints,
                vessel_id: vessel.id,
                distance: totalDistance,
                avg_speed: speeds.reduce((a, b) => a + b, 0) / speeds.length,
                max_speed: Math.max(...speeds),
                selected: true
            };
        } catch (error) {
            console.error(`Failed to load track for vessel ${vessel.id}:`, error);
            return null;
        }
    }

    /**
     * 선박 선택 토글
     */
    toggleSelection(vesselId) {
        if (this.selectedVessels.has(vesselId)) {
            this.selectedVessels.delete(vesselId);
        } else {
            this.selectedVessels.add(vesselId);
        }
        
        this.onSelectionChange?.(this.selectedVessels);
        return this.selectedVessels.has(vesselId);
    }

    /**
     * 전체 선택
     */
    selectAll() {
        this.vesselList.forEach(v => this.selectedVessels.add(v.id));
        this.onSelectionChange?.(this.selectedVessels);
    }

    /**
     * 전체 해제
     */
    deselectAll() {
        this.selectedVessels.clear();
        this.onSelectionChange?.(this.selectedVessels);
    }

    /**
     * 선택 초기화
     */
    clearSelection() {
        this.selectedVessels.clear();
        this.tracks = [];
        this.onSelectionChange?.(this.selectedVessels);
    }

    /**
     * 정렬 및 필터 적용
     */
    sortAndFilter() {
        // 필터 적용
        let filtered = this.vesselList.filter(v => 
            passesFilters(v, this.filters)
        );
        
        // 정렬
        filtered.sort((a, b) => {
            let compareValue = 0;
            
            switch(this.sortBy) {
                case 'id':
                    compareValue = a.id.localeCompare(b.id);
                    break;
                case 'speed':
                    compareValue = a.avg_speed - b.avg_speed;
                    break;
                case 'distance':
                    compareValue = a.distance - b.distance;
                    break;
            }
            
            return this.sortOrder === 'asc' ? compareValue : -compareValue;
        });
        
        return filtered;
    }

    /**
     * 필터 설정
     */
    setFilters(filters) {
        this.filters = { ...this.filters, ...filters };
    }

    /**
     * 필터 초기화
     */
    resetFilters() {
        this.filters = {
            minSpeed: 0,
            maxSpeed: 50,
            minDist: 0,
            maxDist: 200
        };
    }

    /**
     * 정렬 설정
     */
    setSort(sortBy, sortOrder) {
        this.sortBy = sortBy;
        this.sortOrder = sortOrder;
    }

    /**
     * 선박 목록 렌더링 (HTML 생성)
     */
    renderVesselList() {
        const filtered = this.sortAndFilter();
        
        if (filtered.length === 0) {
            return '<div class="text-muted text-center p-3">선박이 없습니다</div>';
        }
        
        let html = `<div class="mb-2 text-muted">총 ${filtered.length}척</div>`;
        
        filtered.forEach(vessel => {
            const isSelected = this.selectedVessels.has(vessel.id);
            
            html += `
                <div class="vessel-item ${isSelected ? 'selected' : ''}" 
                     data-vessel-id="${vessel.id}">
                    <input type="checkbox" 
                           class="vessel-checkbox"
                           data-vessel-id="${vessel.id}"
                           ${isSelected ? 'checked' : ''}>
                    <div class="vessel-info">
                        <strong>${vessel.id}</strong>
                        <small>
                            거리: ${formatDistance(vessel.distance)} | 
                            평균속도: ${formatSpeed(vessel.avg_speed)}
                        </small>
                    </div>
                </div>
            `;
        });
        
        return html;
    }

    /**
     * 선박 통계 가져오기
     */
    getStatistics() {
        const filtered = this.sortAndFilter();
        
        if (filtered.length === 0) {
            return {
                count: 0,
                totalDistance: 0,
                avgSpeed: 0,
                maxSpeed: 0
            };
        }
        
        const totalDistance = filtered.reduce((sum, v) => sum + v.distance, 0);
        const avgSpeed = filtered.reduce((sum, v) => sum + v.avg_speed, 0) / filtered.length;
        const maxSpeed = Math.max(...filtered.map(v => v.max_speed || v.avg_speed));
        
        return {
            count: filtered.length,
            totalDistance,
            avgSpeed,
            maxSpeed
        };
    }

    /**
     * 이벤트 핸들러 설정
     */
    setEventHandlers(handlers) {
        this.onSelectionChange = handlers.onSelectionChange;
    }

    /**
     * 상태 초기화
     */
    reset() {
        this.vesselList = [];
        this.selectedVessels.clear();
        this.tracks = [];
        this.currentArea = null;
        this.resetFilters();
    }

    // Getters
    getSelectedVessels() {
        return this.selectedVessels;
    }

    getSelectedCount() {
        return this.selectedVessels.size;
    }

    getTracks() {
        return this.tracks;
    }

    getCurrentArea() {
        return this.currentArea;
    }

    getVesselList() {
        return this.vesselList;
    }
}