import PolymorphicIdentifier  from "src/client/poid.js"
import BibliographyScheme from "./bibliography-scheme.js";
import FileIndex from "src/client/fileindex.js"

import Literature from "src/client/literature.js"

import Bibliography from 'src/client/bibliography.js'
import Strings from 'src/client/strings.js'  


export class BibScheme extends BibliographyScheme {
  
  get scheme() {
    return "bib"
  }
  
  async searchEntries(entries, query) {
    var key = query
    return entries.filter(entry => entry.key == key)
  }
  
  
  async content(entries, query) {
    entries = entries.sortBy(ea => ea.doi)
    var entry = entries.filter(ea => !ea.url.match(/_marker/))[0]
    
    if (!entry) entry =  entries[0] // only used citation bibs if there are  no real ones
    if (!entry) entry = {authors: undefined, keywords: undefined, title: ""}
    
   
    
    var key = query
    var files = await FileIndex.current().db.files.where("bibkey").equals(key).toArray()
    var literatureNotes = await FileIndex.current().db.files
      .filter( ea => ea.name.match(key + ".md")).toArray()

    var papers = await Literature.alexdb.papers
                        .where("key").equals(key)
                        .or("doi").equals(entry.doi || "nomatch")
                        .toArray()
    papers = papers.filter(ea => ea.alexid) // scholarid is limited, so we use openalex for now

    
    var content = `<h2>[${key}]<br/>${
        entry.authors ? 
          entry.authors.map(ea => `<a href="author://${ea}">${ea}</a>` ).join(", ") + ".": ""
        }  ${entry.year|| ""}<br/><i> ${entry.title|| ""} </i></h2>`
  
    
  
    
    if (papers.length > 0) {
      content += "<div>" + papers.map(ea => {
        return `<literature-paper mode="short" alexid="${ea.alexid}"></literature-paper>`   
      }).join(" ") + "</div><br>"      
    } else if(entry.alexid) {
      content += "<div>" + `<a href="alex://browse/${entry.alexid}">[OpenAlex]</a>` + "</div><br>"
    } else if(entry.doi) {
      content += "<div>" + `<a href="alex://browse/works?filter=doi:${Literature.extractDOI(entry.doi)}">[OpenAlex DOI]</a>` + "</div><br>"
    } else if (entry.title) {
      content += "<div>" + `<a href="alex://browse/works?filter=title.search:${entry.title}">[Search OpenAlex]</a>` + "</div><br>"
      // content += "<div>" + `<a href="scholar://browse/paper/search?query=${entry.title}">[search scholar]</a>` + "</div><br>"
    }

    var file = files[0]
    var generatedKeywords = []
    if (file) {
      let dir = lively.files.directory(file.url)
      var basename = new URL(file.url).pathname.replace(/.*\//,"").replace(/\..*/,"")
      
      let keywordsURL = dir + "_marker/" + basename + "/" + basename + ".keywords"

      let keywordFiles = await FileIndex.current().db.files.where("url").equals(keywordsURL).toArray()
      if (keywordFiles[0]) { 
        generatedKeywords = keywordFiles[0].keywords
      } 
  
      if (entry.keywords  || generatedKeywords.length > 0) {
        let keywords = entry.keywords ? entry.keywords : []
        generatedKeywords = generatedKeywords.filter(ea => !keywords.includes(ea))

        content += `<div><b>Keywords:</b> ${keywords.concat(generatedKeywords)
          .map(ea => `<a href="keyword://${ea}">${generatedKeywords.includes(ea) ? "<i>"+ea+"</i>" : ea}</a>`)
          .join(", ") } </div>`
      }
      if (entry.source) {
        content += "<pre>" + entry.source+ "</pre>"
      }         
      content += "<h3>Documents</h3><ul>" + (files.concat(literatureNotes)).map(ea => {
        return `<li><a href="${ea.url}">${ea.name}</a></li>`     
      }).join("\n") + "</ul>"


      content += "<h3>Bibliographies</h3><ul>" + entries
        .filter(ea => !ea.url.match(/_marker/))
        .map(ea => {
        return `<li><a href="${ea.url}">${ea.url}</a></li>`     
      }).join("\n") + "</ul>"  



      content += "<h3>Citations</h3><ul>" + entries
        .filter(ea => ea.url.match(/_marker/))
        .map(ea => {
          let key = Bibliography.urlToKey(ea.url)
        return `<li><a href="bib://${key}">${key}</a></li>`     
      }).join("\n") + "</ul>"  
    
   
      let bibURL = dir + "_marker/" + basename + "/" + basename + ".bib"
      if (await lively.files.exists(bibURL)) {
        content += "<h3>References</h3>"   
        let references = await fetch(bibURL).then(r => r.text())
        content += "<lively-bibtex>" + references.replace(/</g, "&lt;") + "</lively-bibtex>"
      }
    
      // content += "Generated Keywords: " + keywords
    }
    
    
    return content
  }
}

PolymorphicIdentifier.register(BibScheme)