import { Component, OnInit } from '@angular/core';
import { BookService } from '../services/book.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page  implements OnInit {
  books: any[] = [];
  searchQuery: string = '';
  selectedType: string = '';
  bookTypes: string[] = [];
  sortByBorrowTimes: boolean = false;

  constructor(
    private bookService: BookService,
    private router: Router
  ) {}

  ngOnInit() {
    this.fetchBooks();
  }

  async fetchBooks() {
    const queryParams = {
      title: this.searchQuery,
      type: this.selectedType,
      sortByBorrowTimes: this.sortByBorrowTimes
    };
    this.books = await this.bookService.getBooks(queryParams);
  }

  toggleSort() {
    this.sortByBorrowTimes = !this.sortByBorrowTimes;
    this.fetchBooks();
  }

  onClick(event: MouseEvent, i: number): void {
    let book = this.books[i];
    let path = "details-book/" + book.id;
    this.router.navigate([path]);
  }
}
