import { SensorData } from '../services/api';

export interface ExportOptions {
  format: 'csv' | 'json';
  includeHeaders?: boolean;
  dateRange?: {
    start: string;
    end: string;
  };
}

/**
 * 센서 데이터를 CSV 형식으로 변환
 */
const convertToCSV = (data: SensorData[], includeHeaders: boolean = true): string => {
  if (data.length === 0) return '';

  const headers = [
    'ID', 'Device ID', 'Node ID', 'Temperature (°C)', 'Humidity (%)',
    'Longitude', 'Latitude', 'PM10 (μg/m³)', 'PM2.5 (μg/m³)',
    'Pressure (hPa)', 'Illumination (lux)', 'TVOC (ppb)',
    'CO2 (ppm)', 'O2 (%)', 'CO (ppm)', 'Recorded Time', 'Received Time'
  ];

  const rows = data.map(item => [
    item.id,
    item.device_id,
    item.node_id,
    item.temperature,
    item.humidity,
    item.longitude,
    item.latitude,
    item.pm10 || '',
    item.pm25 || '',
    item.pressure || '',
    item.illumination || '',
    item.tvoc || '',
    item.co2 || '',
    item.o2 || '',
    item.co || '',
    item.recorded_time,
    item.received_time
  ]);

  let csv = '';
  
  if (includeHeaders) {
    csv += headers.join(',') + '\n';
  }
  
  csv += rows.map(row => 
    row.map(cell => 
      typeof cell === 'string' && cell.includes(',') 
        ? `"${cell}"` 
        : cell
    ).join(',')
  ).join('\n');

  return csv;
};

/**
 * 센서 데이터를 JSON 형식으로 변환
 */
const convertToJSON = (data: SensorData[]): string => {
  return JSON.stringify(data, null, 2);
};

/**
 * 데이터를 파일로 다운로드
 */
const downloadFile = (content: string, filename: string, mimeType: string) => {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

/**
 * 센서 데이터 내보내기
 */
export const exportSensorData = (
  data: SensorData[], 
  options: ExportOptions
): void => {
  const { format, includeHeaders = true, dateRange } = options;
  
  // 날짜 범위 필터링
  let filteredData = data;
  if (dateRange) {
    filteredData = data.filter(item => {
      const recordedTime = new Date(item.recorded_time);
      const start = new Date(dateRange.start);
      const end = new Date(dateRange.end);
      return recordedTime >= start && recordedTime <= end;
    });
  }

  // 파일명 생성
  const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
  const filename = `sensor-data-${timestamp}.${format}`;

  let content: string;
  let mimeType: string;

  if (format === 'csv') {
    content = convertToCSV(filteredData, includeHeaders);
    mimeType = 'text/csv;charset=utf-8;';
  } else {
    content = convertToJSON(filteredData);
    mimeType = 'application/json;charset=utf-8;';
  }

  downloadFile(content, filename, mimeType);
};

/**
 * 현재 페이지의 센서 데이터 내보내기 (Dashboard용)
 */
export const exportCurrentData = (
  data: SensorData[], 
  format: 'csv' | 'json' = 'csv'
): void => {
  exportSensorData(data, { format });
}; 