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

@Component({
  selector: 'query-information',
  templateUrl: './query-information.component.html',
  styleUrls: ['./query-information.component.css']
})
export class QueryInformationComponent implements OnInit {
  currPage: number = 1;
  userDetails;
  articleClicks;
  feedbackInteractions;
  globalProperties;
  firstStepResults;
  mergedResults;
  sortBy;

  filtersLoaded: Promise<boolean>;

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

  //This function gets called when the page loads
  //Returns the user profile
  ngOnInit() {
    this.sortBy = { sortBy: "query_searches"};

    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res["user"];
      },
      err => {}
    );
    this.userService.getAllGlobalProperties(this.sortBy).subscribe(
      res => {
        this.globalProperties = res["globalProperties"];
        // this.globalProperties = JSON.parse(this.globalProperties);
        this.filtersLoaded = Promise.resolve(true); // Setting the Promise as resolved
      },
      err => {}
    );
  }

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

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

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

  //This function allows the user to export the table as a CSV file
  onExport() {
    this.userService.downloadTable(this.globalProperties, "query-information");
  }
}
