import { Component, OnInit } from "@angular/core";
import { UserService } from "../../shared/user.service";
import { Router } from "@angular/router";
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-saved-articles',
  templateUrl: './saved-articles.component.html',
  styleUrls: ['./saved-articles.component.css'],
    

})
export class SavedArticlesComponent implements OnInit {

  userDetails;
  
  constructor(private userService: UserService, private router: Router) {}

  /**
   * This function is called when the page loads.
   * It will return the user information from the database
   */
  ngOnInit() {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res["user"];
      },
      err => {}
    );


  }

  //This function allows the user to logout from their profile page
  onLogout() {
    this.userService.deleteToken();
    this.router.navigate(["/login"]);
  }

  //This function redirects the user to the savedarticles page
  savedArticles(userDetails) {
    if (!this.userService.isLoggedIn()) {
      this.router.navigate(["/login"]);
    } else {
      this.router.navigate(["/savedarticles"]);
    }
  }

  //this function allows the user to remove article from saved articles
  unsaveArticle(
    article_id: number,
    title: string,
    authors: Array<string>,
    year: string,
    abstract: string,
    article_url:string,
    index
  ) {
    var articleInfo = {
      articles: {article_id, title, authors, year, abstract,article_url }
    };
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res["user"];
        this.userService.removeArticle(articleInfo).subscribe(()=>{
          this.userDetails.articles.splice(index, 1);
      });

      },
      err => {}
    );
  }

  //Gets called when the user clicks on the cite button under articles
  toggle_cite(id) {
    var e = document.getElementById(id);
    if (e.style.display == "block") {
      e.style.display = "none";
    } else {
      e.style.display = "block";
    }
  }
  //Gets called when the user clicks on the share button under articles
  share(id) {
    var e = document.getElementById(id);
    if (e.style.display == "block") {
      e.style.display = "none";
    } else {
      e.style.display = "block";
    }
  }
  //Takes the user to the Profile page 
  profile() {
    if (!this.userService.isLoggedIn()) {
      this.router.navigate(["/login"]);
    } else {
      this.router.navigate(["/userprofile"]);
    }
  }  
}
