import { Component } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  LoadingController
} from "ionic-angular";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import { TwitterApiProvider } from "../../providers/twitter-api/twitter-api";
import { Storage } from "@ionic/storage";
import { P2pStorageIpfsProvider } from "../../providers/p2p-storage-ipfs/p2p-storage-ipfs";
import { P2pDatabaseGunProvider } from "../../providers/p2p-database-gun/p2p-database-gun";

@IonicPage()
@Component({
  selector: "page-write-tweet",
  templateUrl: "write-tweet.html"
})
export class WriteTweetPage {
  tweet: FormGroup;
  retweetId: string;
  retweet;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private formBuilder: FormBuilder,
    private twitter: TwitterApiProvider,
    private loadingCtrl: LoadingController,
    private storage: Storage,
    private ipfs: P2pStorageIpfsProvider,
    private gun: P2pDatabaseGunProvider
  ) {
    this.retweetId = this.navParams.get("tweetId");
    this.tweet = this.formBuilder.group({
      text: ["", Validators.maxLength(140)],
      p2p: [false]
    });
  }

  async ionViewDidLoad() {
    if (this.retweetId) {
      this.retweet = await this.twitter.fetchTweet(this.retweetId);
    }
  }

  get tweetCharProgress() {
    let progress = 1 - this.tweet.value["text"].length / 140;
    let radius = 8;
    let circumference = Math.PI * radius * 2;
    return progress * circumference;
  }

  async submitTweet() {
    const loading = this.loadingCtrl.create();
    loading.present();

    if (this.tweet.value.p2p) {
      const tweet = await this.buildPrivateTweet();
      const res = await this.ipfs.storeTweet(tweet);
      this.gun.storeLastTweetHashForUser(
        tweet.user_id,
        res["Hash"],
        tweet.created_at
      );
    } else {
      await this.twitter.tweet(this.tweet.value["text"], this.retweet);
    }

    loading.dismiss();
    this.navCtrl.pop();
  }

  private async buildPrivateTweet() {
    const status = this.tweet.value["text"].trim();
    return {
      full_text: status,
      user_id: await this.storage.get("userId"),
      created_at: Date.now(),
      private_tweet: true,
      display_text_range: [0, status.length],
      entities: {}
    };
  }
}
