import hljs from 'highlight.js'

const EXTENSION_LANGUAGE = {
  css: 'css',
  htm: 'xml',
  html: 'xml',
  js: 'javascript',
  json: 'json',
  md: 'markdown',
  scad: 'openscad',
  svg: 'xml',
  ts: 'typescript',
  xml: 'xml',
}

const CONTENT_TYPE_LANGUAGE = {
  html: 'xml',
  svg: 'xml',
  stl: 'openscad',
}

function languageOrPlaintext(language) {
  return language && hljs.getLanguage(language) ? language : 'plaintext'
}

function extensionOf(value) {
  const clean = String(value || '').split('?')[0].split('#')[0]
  return clean.includes('.') ? clean.split('.').pop().toLowerCase() : ''
}

export function sourceLanguage(item = {}) {
  const filename = item.source_filename || item.filename || item.url || ''
  const language = EXTENSION_LANGUAGE[extensionOf(filename)] || CONTENT_TYPE_LANGUAGE[item.content_type]
  return languageOrPlaintext(language)
}

export function highlightSource(source, language) {
  return hljs.highlight(source || '', { language: languageOrPlaintext(language) }).value
}
