import { request } from '../client.mjs'

export default class GitProvider {
  constructor(config, requester = request) {
    this.config = config
    this.requestConfig = GitProvider.getRequestConfig(config)
    this.requester = requester
  }

  async getLatestVersion() {
    let res = await this.requester(this.requestConfig, this.config.url)
      .catch(function(err) {
        return Promise.reject(new Error('Failed to get release information, got ' + err.message))
      })

    if (!Array.isArray(res.body)) {
      return Promise.reject(new Error('Body was not a valid git repository release data: ' + JSON.stringify(res.body)))
    }

    let checked = 0

    for (let item of res.body) {
      if (!Array.isArray(item.assets)) continue

      checked++

      for (let asset of item.assets) {
        if (!asset.name.endsWith('-sc.7z')) continue
        if (this.config.git_required_prefix && !asset.name.startsWith(this.config.git_required_prefix)) continue

        return {
          version: item.name,
          link: asset.browser_download_url,
          filename: asset.name,
          description: item.body,
          log: '',
        }
      }
    }
    return Promise.reject(new Error(`No valid service-core release was found, checked ${checked} releases.`))
  }

  downloadVersion(version, target){
    return this.requester(this.requestConfig, version.link, target)
  }

  static getRequestConfig(config) {
    if (config.token) {
      return { token: config.token }
    }
    return {}
  }

  async checkConfig() {
    if (!this.config.url) return Promise.reject(new Error('url was missing in git provider'))
    if (typeof(this.config.url) !== 'string') return Promise.reject(new Error('url was not a valid url'))
    try { new URL(this.config.url) }
    catch (err) { return Promise.reject(new Error('url was not a valid url: ' + err.message)) }
  }
}
