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) {}

  /**
   * Store private tweet on ipfs
   * @param tweet tweet object
   */
  public storeTweet(tweet) {
    return this.storeOnIPFS(tweet);
  }

  /**
   * Store public key history on ipfs
   * @param publicKeyHistory public key history object
   */
  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();
  }

  /**
   * fetch data from ipfs for hash
   * @param hash address hash
   */
  public async fetchJson(hash: string) {
    const options = {
      params: { arg: hash }
    };

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

  /**
   * fetch tweet from ipfs for hash
   * @param hash address hash
   */
  public fetchTweet(hash: string): Promise<string> {
    const options = {
      params: { arg: hash }
    };

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

  /**
   * fetch multiple tweets from ipfs
   * @param hashs array of hashes
   */
  public async fetchTweets(hashs: string[]): Promise<string[]> {
    return await Promise.all(hashs.map(hash => this.fetchTweet(hash)));
  }
}
