import { Component, OnInit } from '@angular/core';
import { UserService } from "../../shared/user.service";
import { Router } from "@angular/router";

@Component({
  selector: 'app-article-info',
  templateUrl: './article-info.component.html',
  styleUrls: ['./article-info.component.css']
})
export class ArticleInfoComponent implements OnInit {
  userDetails;
  articleProperties;
  filtersLoaded : Promise<boolean>;

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

  //This function gets called when the page loads
  //Returns the user profile
  ngOnInit() {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res["user"];
      },
      err => {}
    );

    this.userService.getArticleInfoProperties({sortBy : "article_clicks"}).subscribe(
      res => {
        this.articleProperties = res["articleProperties"];
        this.filtersLoaded = Promise.resolve(true);

      },
      err => {}
    );
  }


  //Redirects to the profile page
  profile() {
    if (!this.userService.isLoggedIn()) {
      this.router.navigate(["/login"]);
    } else {
      this.router.navigate(["/userprofile"]);
    }
  }

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

  //Allows you to logout from the Click History page
  onLogout() {
    this.userService.deleteToken();
    this.router.navigate(["/login"]);
  }

  onExport() {
    this.userService.downloadTable(this.articleProperties, "article-ratings");
  }


}
