import { Injectable } from "@angular/core";
import { Storage } from "@ionic/storage";
import { Platform } from 'ionic-angular';
import { File } from '@ionic-native/file';
import { HttpClient } from "@angular/common/http";
import * as tweets from './tweet.json';
declare var cordova: any;

@Injectable()
export class MockProvider {
  friends;
  userId: string;
  mockTweets;
  result;
  fileRead: Boolean;

  constructor(
    private storage: Storage,
    private file: File,
    public http: HttpClient,
    private platform: Platform
  ) {
    console.log('tweets are:', tweets);
    this.fileRead = false;
    this.mockTweets = [...tweets];
    console.log(' this.mockTweets are:', this.mockTweets);

    this.storage.get("userId").then(userId => (this.userId = userId));
  }

  /**
   * Retrives the public and private tweets for a user
   * Since it is loaded in batches of 20 public tweets, public and private tweet are used as reference to load next 20 tweets
   * @param userId user id
   * @param oldestPublicTweet oldest public tweet
   * @param oldestPrivateTweet oldest private tweet
   */
  public async loadUserTimeline(
    userId,
    oldestPublicTweet ? ,
    oldestPrivateTweet ?
  ) {

  }

  /**
   * Retrieves the home feed for the logged in user
   * Since it is loaded in batches of 20 public tweets, public and private tweet are used as reference to load next 20 tweets
   * @param oldestPublicTweet oldest public tweet
   * @param oldestPrivateTweet oldest private tweet
   */
  public async loadHomeTimeline(oldestPublicTweet ? , oldestPrivateTweet ? ) {
    console.log('hometime line called in mockprovider');
    this.readFile().then(tweets => {
        console.log('new mocktweets after replace', this.mockTweets);
      })
      .catch(err => console.error('error in readfile', err));
    return this.mockTweets;
  }

  public async replyTweet() {}


  public writeTweet(twt: string, isPrivate: boolean, retwt, reply) {
    console.log('inside writetweet', retwt, reply);
    let newTweet = Object.assign({}, this.mockTweets[0]);
    newTweet.full_text = twt;
    newTweet.id = Math.floor(100000 + Math.random() * 900000);
    newTweet.id_str = newTweet.id;
    newTweet.full_text = twt;
    if(retwt){
      newTweet.is_quote_status = true;
      newTweet.quoted_status = retwt;
      newTweet.quoted_status_id = retwt.id;
      newTweet.quoted_status_id_str = retwt.id_str;
    }
    if(reply){
      newTweet.in_reply_to_screen_name=reply.user.name;
      newTweet.in_reply_to_status_id = reply.id;
      newTweet.in_reply_to_status_id_str = reply.id_str;
      newTweet.in_reply_to_user_id = reply.user.id;
      newTweet.in_reply_to_user_id_str = reply.user.id_str;
    }
    if (isPrivate) {
      newTweet.private_tweet = true;
    }
    console.log('new tweet ', newTweet);
    this.mockTweets.push(newTweet);
    this.writefile(this.mockTweets);
  }

  public async writefile(mocktweet) {
    await this.platform.ready()
      .then(_ => console.log('Device ready.'));
    //check if file exists
    this.result = this.file.writeFile(this.file.dataDirectory, 'twets.json', JSON.stringify(mocktweet), { replace: true, append: false });
    console.log("writing the file:", this.result);
    console.log('Reading the file:', this.readFile());
  }

  public async readFile() {
    var readTweets: [];
    console.log('in readfile', this.mockTweets);
    this.file.checkFile(this.file.dataDirectory, 'twets.json')
      .then(() => {
        console.log('file exists');
        this.file.readAsText(this.file.dataDirectory, 'twets.json')
          .then(data => {
            readTweets = JSON.parse(data);
            if (!this.fileRead) {
              // readTweets.forEach(el=>this.mockTweets.push(el));
              this.mockTweets = [...readTweets];
              this.fileRead = true;
            }
            console.log('file is: ', this.mockTweets);
          })
          .catch(err => console.error('error in reading file', err));
      })
      .catch(err => {
        console.error('File doesnt exist', err);
        this.file.writeFile(this.file.dataDirectory, 'twets.json', JSON.stringify(this.mockTweets), { replace: true });
      });
  }

  public likeTweet(id) {
    console.log('fetch tweet id:', id, this.mockTweets);
    const result = this.mockTweets.find(x => x.id_str == id);
    // this.mockTweets.forEach(el=>{
    //   console.log("mocktweet el is:",el);
    // })
    result.favorited = true;
    result.favorite_count++;
    console.log('tweet found and modified:', result);
    return result;
  }

  public unlikeTweet(id) {
    console.log('fetch tweet id:', id, this.mockTweets);
    const result = this.mockTweets.find(x => x.id_str == id);
    // this.mockTweets.forEach(el=>{
    //   console.log("mocktweet el is:",el);
    // })
    result.favorited = false;
    result.favorite_count--;
    console.log('tweet found and modified:', result);
    return result;
  }


  public fetchTweet(tweetID) {
    return this.mockTweets.find(x => x.id_str == tweetID);
  }

  private async fetchPrivateTweets(privateTweetsData: object[]) {

  }


}
