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

@Component({
  selector: 'app-query-history',
  templateUrl: './query-history.component.html',
  styleUrls: ['./query-history.component.css']
})
export class QueryHistoryComponent implements OnInit {
  query: string = window.location.search.substring(1).split("=")[1];
  userDetails;
  querySearches;
  filtersLoaded : Promise<boolean>;
  currentPage: number = 0;
  numQueries: number = 7;
  totalItems;
  // currentPage: number = 0;
  // numQueries: number = 7;

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

  //This function gets called when the page loads
  //Returns the user profile
  ngOnInit() {
    // var query: string = window.location.search.substring(1).split("=")[1];
    var query: string = window.location.search.slice(1);

    //URL parameters stored here
    var paramObj = {};
    if(true) {
      //everything after # is not part of our query string, so remove it
      query = query.split('#')[0];
      
      //split our query into its component parts
      var arr = query.split('&');
      
      for(var i = 0; i < arr.length; i++) {
        // separate all keys and values
        var a = arr[i].split('=');

        var paramName = a[0];
        var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
        //if doesn't exist, create property
        if(!paramObj[paramName]) {
          paramObj[paramName] = paramValue;
        } else if (paramObj[paramName] && typeof paramObj[paramName] === 'string'){
          // if property does exist and it's a string, convert it to an array
          paramObj[paramName] = [paramObj[paramName]];
          paramObj[paramName].push(paramValue);
        } else {
          // otherwise add the property
          paramObj[paramName].push(paramValue);
        }
      }
    }
    
    this.query = paramObj["page"];

    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res["user"];
        
      },
      err => {}
    );
    
    var currPageState = {
      currentPage: (parseInt(this.query) - 1) * 7,
      numQueries: this.numQueries
    }

    this.userService.getQuerySearchCount().subscribe(
      res => {
        this.totalItems = res["searchcount"];
        this.totalItems = this.totalItems[0].count;
        //Stores query information to the query history developer stat
        this.userService.getGlobalQuerySearches(currPageState).subscribe(
          res => {
            this.querySearches = res["querySearches"];
            this.userService.getObjectDate(this.querySearches).subscribe(
              res => {
                this.querySearches = res["result"];
                this.filtersLoaded = Promise.resolve(true);
              },
              err => {}
            );
          },
          err => {}
        );
      });

  }


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

  /**
   *
   * This function gets called when a user clicks on a new page number.
   * options. It redirects the user to a page that includes the page number,
   * making sure to keep the current filter state.
  */
  goToPage(p: number) {
    var queryURI = "./queryhistory?page=" + p;
    window.location.href = queryURI;
  }

  //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"]);
  }

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

