import Request from 'request-promise'
import { parseString } from 'xml2js'

export default class JackettAPI {
  constructor (options) {
    this.apiKey = options.apiKey
    this.endpoint = options.endpoint
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
  }

  _getUrl (query, category, count) {
    return `${this.endpoint}?apikey=${this.apiKey}&t=search&cat=${category}&q=${query}`
  }

  _getCat (category) {
    switch (category) {
      case 'TV':
        return "5000,5020,5030,5040,5045,5050,5060,5070,5080"
      case 'Movie':
      default:
        return "2000,2010,2020,2030,2040,2045,2050,2060"
    }
  }

  _formatItem (item) {
    return {
      title: item.title[0],
      seeds: item['torznab:attr'].filter((attr) => attr['$'].name === 'seeders')[0]['$'].value,
      peers: item['torznab:attr'].filter((attr) => attr['$'].name === 'peers')[0]['$'].value,
      size: item.size[0],
      link: item.link[0]
    }
  }

  _parseResult (data) {
    return new Promise((resolve, reject) => {
      data = parseString(data, (err, json) => {
        if (err) {
          return reject(err)
        }

        let torrents = []
        if (json.rss.channel[0].hasOwnProperty('item')) {
          torrents = json.rss.channel[0].item.map((item) => this._formatItem(item))
        }

        resolve(torrents)
      })
    })
  }

  search (query, category, count) {
    return new Promise((resolve, reject) => {
      let url = this._getUrl(query, category, count)

      let options = {
        uri: this.endpoint,
        qs: {
            method: "GET",
            strictSSL: false,
            apikey: this.apiKey,
            t: 'search',
            cat: this._getCat(category),
            q: query
        },
        json: true
      }

      Request(options).then((data) => {
        return this._parseResult(data)
      }).then(resolve).catch(reject)
    })
  }

  getMagnet (torrent) {
    return new Promise((resolve, reject) => {
      resolve(torrent.link)
    })
  }
}
@@ -615,16 +615,270 @@
  %7D%0A  %7D%0A%0A
+  _getSizeItem (bytes) %7B%0A    var sizes = %5B'o', 'ko', 'mo', 'go', 'to'%5D%0A    if (bytes === 0) %7B return '0 b' %7D%0A    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10)%0A    return %60$%7BMath.round(bytes / Math.pow(1024, i), 2)%7D $%7Bsizes%5Bi%5D%7D%60%0A  %7D%0A%0A
   _forma
@@ -888,24 +888,24 @@
 em (item) %7B%0A
-
     return %7B
@@ -1135,16 +1135,34 @@
   size: 
+this._getSizeItem(
 item.siz
@@ -1161,24 +1161,25 @@
 item.size%5B0%5D
+)
 ,%0A      link

format size from jackett