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

@Injectable()
export class P2pStorageIpfsProvider {
  private infuraUrl = "https://ipfs.infura.io:5001/api/v0/";

  constructor(public http: HttpClient) {}

  public storeTweet(tweet) {
    return this.storeOnIPFS(tweet);
  }

  public storePublicKey(publicKeyHistory) {
    return this.storeOnIPFS(publicKeyHistory);
  }

  private storeOnIPFS(json) {
    const formData = new FormData();
    formData.append("data", JSON.stringify(json));

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

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

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

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

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

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