/**
 * EPG (XMLTV) 解析器
 * 支持标准 XMLTV 格式
 */

export function parseEPG(xmlText) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(xmlText, 'text/xml')
  
  const programmes = []
  const programmeNodes = doc.querySelectorAll('programme')
  
  programmeNodes.forEach(node => {
    const programme = {
      channel: node.getAttribute('channel'),
      start: parseXMLTVTime(node.getAttribute('start')),
      stop: parseXMLTVTime(node.getAttribute('stop')),
      title: getTextContent(node, 'title'),
      desc: getTextContent(node, 'desc'),
      category: getTextContent(node, 'category'),
      icon: getAttribute(node, 'icon', 'src')
    }
    programmes.push(programme)
  })
  
  // 按频道分组
  const epgByChannel = {}
  programmes.forEach(p => {
    if (!epgByChannel[p.channel]) {
      epgByChannel[p.channel] = []
    }
    epgByChannel[p.channel].push(p)
  })
  
  // 每个频道按时间排序
  Object.keys(epgByChannel).forEach(channel => {
    epgByChannel[channel].sort((a, b) => a.start - b.start)
  })
  
  return epgByChannel
}

// XMLTV 时间格式: 20240104120000 +0800
function parseXMLTVTime(timeStr) {
  if (!timeStr) return null
  
  // 提取年月日时分秒和时区
  const year = timeStr.substring(0, 4)
  const month = timeStr.substring(4, 6)
  const day = timeStr.substring(6, 8)
  const hour = timeStr.substring(8, 10)
  const minute = timeStr.substring(10, 12)
  const second = timeStr.substring(12, 14)
  
  return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`)
}

function getTextContent(node, tagName) {
  const child = node.querySelector(tagName)
  return child?.textContent || ''
}

function getAttribute(node, tagName, attrName) {
  const child = node.querySelector(tagName)
  return child?.getAttribute(attrName) || ''
}

// 获取当前正在播放的节目
export function getCurrentProgramme(epgList) {
  if (!epgList || epgList.length === 0) return null
  
  const now = new Date()
  return epgList.find(p => now >= p.start && now < p.stop)
}

// 获取下一个节目
export function getNextProgramme(epgList) {
  if (!epgList || epgList.length === 0) return null
  
  const now = new Date()
  return epgList.find(p => p.start > now)
}

// 格式化时间显示
export function formatTime(date) {
  if (!date) return ''
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 格式化日期显示
export function formatDate(date) {
  if (!date) return ''
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric'
  })
}

// 计算节目进度百分比
export function getProgrammeProgress(programme) {
  if (!programme) return 0
  
  const now = new Date()
  const total = programme.stop - programme.start
  const elapsed = now - programme.start
  
  return Math.min(100, Math.max(0, (elapsed / total) * 100))
}

// 模拟 EPG 数据（测试用）
export function generateMockEPG(channelId) {
  const programmes = []
  const now = new Date()
  const baseTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
  
  for (let i = 0; i < 24; i++) {
    const start = new Date(baseTime.getTime() + i * 60 * 60 * 1000)
    const stop = new Date(start.getTime() + 60 * 60 * 1000)
    
    programmes.push({
      channel: channelId,
      start,
      stop,
      title: `节目 ${i + 1}`,
      desc: `这是第 ${i + 1} 个节目的简介描述`,
      category: i % 3 === 0 ? '新闻' : (i % 3 === 1 ? '电视剧' : '综艺')
    })
  }
  
  return programmes
}
