import { Injectable } from '@angular/core'

@Injectable({
  providedIn: 'root'
})
export class DeployService {
  constructor() {}

  public downloadFile(
    content: any,
    filename: string,
    extension: string = 'txt'
  ) {
    let jobBlob = new Blob([content], {
      type: 'text/plain'
    })

    if (navigator.appVersion.toString().indexOf('.NET') > 0) {
      window.navigator.msSaveBlob(jobBlob, `${filename}.${extension}`)
    } else {
      let downloadLink = document.createElement('a')
      downloadLink.href = 'data:text/plain,' + encodeURIComponent(content)
      downloadLink.download = `${filename}.${extension}`
      document.body.appendChild(downloadLink)
      downloadLink.click()
      document.body.removeChild(downloadLink)
    }
  }

  public readFile(file: File): Promise<any> {
    return new Promise((resolve, reject) => {
      let JsonFileReader = new FileReader()

      JsonFileReader.onload = () => {
        if (JsonFileReader.result) {
          resolve(JSON.parse(JsonFileReader.result.toString()))
        }
      }

      JsonFileReader.readAsText(file)
    })
  }

  public clearUploadInput(event: Event) {
    ;(<HTMLInputElement>event.target).value = ''
  }
}
