import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";

/*
  Generated class for the P2pStorageIpfsProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class P2pStorageIpfsProvider {
  private infuraUrl = "https://ipfs.infura.io:5001/api/v0/";

  constructor(public http: HttpClient) {}

  public storeTweet(tweet) {
    const formData = new FormData();
    formData.append("data", JSON.stringify(tweet));

    return this.http.post(this.infuraUrl + "add", formData).toPromise();
  }

  public fetchTweet(hash: string) {
    const options = {
      params: { arg: hash }
    };

    return this.http.get(this.infuraUrl + "cat", options).toPromise();
  }

  public async fetchTweets(hashs: string[]) {
    return await Promise.all(hashs.map(hash => this.fetchTweet(hash)));
  }
}
