'use strict'

const path = require('path')
const url = require('url')
const {is} = require('type-is')
const {pipe} = require('mississippi')
const htmlparser = require('htmlparser2')

const {createTempDirectory} = require('../../util/tmpdir')
const bufferize = require('../bufferize')

function getBaseUrls(location) {
  const parsed = new url.URL(location)
  parsed.search = ''

  let baseUrl = parsed.toString()
  const filename = path.basename(baseUrl)

  // If the url ends with a filename, let’s remove it
  if (filename.indexOf('.') > -1) {
    baseUrl = path.dirname(baseUrl)
  }

  parsed.pathname = '/'
  const rootUrl = parsed.toString().slice(0, -1)

  return {baseUrl, rootUrl}
}

async function extractLinks(token, options) {
  let isIndexOf = false
  const links = []

  let {baseUrl, rootUrl} = getBaseUrls(token.finalUrl)

  const parser = new htmlparser.WritableStream({
    ontext: text => {
      const matches = options.indexOfMatches || []

      if (matches.some(match => text.match(match))) {
        isIndexOf = true
      }
    },

    onopentag: (tag, attributes) => {
      if (tag === 'base' && attributes.href) {
        baseUrl = attributes.href
      }

      if (isIndexOf && tag === 'a' && attributes.href && !attributes.href.startsWith('.')) {
        const fullUrl = attributes.href.startsWith('/') ?
          `${rootUrl}${attributes.href}` :
          `${baseUrl}${attributes.href}`

        if (fullUrl.startsWith(baseUrl) && fullUrl !== baseUrl) {
          links.push(fullUrl)
        }
      }
    }
  })

  return new Promise((resolve, reject) => {
    pipe(
      token.response,
      parser,
      err => {
        if (err) {
          return reject(err)
        }

        resolve(links)
      }
    )
  })
}

async function analyzeIndexOf(token, options) {
  if (token.analyzed) {
    return false
  }

  const isHtml = token.fileTypes.some(type => is(type.mime, 'html'))
  if (!isHtml) {
    return false
  }

  options.logger.log('index-of:analyze:start', token)
  const links = await bufferize(token, () => extractLinks(token, options))
  options.logger.log('index-of:analyze:end', token)

  if (links.length > 0) {
    const temporary = await createTempDirectory()

    token.type = 'index-of'
    token.children = links.map(url => ({
      inputType: 'url',
      url,
      temporary
    }))
    token.analyzed = true
  }
}

module.exports = analyzeIndexOf

@@ -1234,44 +1234,116 @@
 href
- && !attributes.href.startsWith('.')
+) %7B%0A        const parsedUrl = url.parse(attributes.href)%0A%0A        let fullUrl%0A        if (parsedUrl.protocol
 ) %7B%0A
@@ -1350,21 +1350,17 @@
         
-const
+ 
  fullUrl
@@ -1377,16 +1377,54 @@
 tes.href
+%0A        %7D else if (parsedUrl.pathname
 .startsW
@@ -1435,10 +1435,11 @@
 '/')
- ?
+) %7B
 %0A   
@@ -1440,24 +1440,34 @@
  %7B%0A         
+ fullUrl =
  %60$%7BrootUrl%7D
@@ -1489,10 +1489,25 @@
 ef%7D%60
- :
+%0A        %7D else %7B
 %0A   
@@ -1512,16 +1512,26 @@
         
+ fullUrl =
  %60$%7Bbase
@@ -1553,16 +1553,26 @@
 s.href%7D%60
+%0A        %7D
 %0A%0A      

Handle full urls in index-of analyzer