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

@Component({
  selector: 'app-navbaraccountsearch',
  templateUrl: './navbaraccountsearch.component.html',
  styleUrls: ['./navbaraccountsearch.component.css']
})
export class NavbaraccountsearchComponent implements OnInit {

  isCollapsedD = false;
  isCollapsedM = false;
  isCollapsedS = false;
  userDetails;
  currentURL;
  query: string = window.location.search.slice(1).split('&')[0].split('=')[1];
  constructor(public userService: UserService, private router: Router) {

    //Gets the curreent query and spaces it
    var spacedQueryArray = this.query.split('%20');

    this.query = spacedQueryArray.join(" ");

    if(window.location.search.slice(1).split('&').length <= 1) {
      this.query = "";
    }
    this.isCollapsedM = true;
    this.isCollapsedS = true;
    this.currentURL = this.router.url;
  }

  ngOnInit() { }

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

  /**
   *
   * This function gets called when a user submits a search
   * It will redirect to the displayresults page with the search query entered
   */
  openSearchPage(form: NgForm) {
    window.location.href =
      "./displayresults?search=" + form.value.search + "&page=1";
  }
}
