import { Component, inject, OnInit } from '@angular/core';
import { BookService } from '../services/book.service';
import { Book } from '../models/book';
import { UserService } from '../services/user.service';
import { FormsModule } from '@angular/forms';
import { User } from '../models/user';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-books',
  standalone: true,
  imports: [FormsModule, DatePipe],
  templateUrl: './books.component.html',
  styleUrl: './books.component.css'
})
export class BooksComponent implements OnInit {

  allBooks: Book[] = []
  message = ""

  private bookService = inject(BookService) 
  private userService = inject(UserService) 

  user: User = new User()

  ngOnInit(): void {
    this.bookService.getAll().subscribe(data=>{
      this.allBooks = data
    })
    let username = localStorage.getItem("loggedUser");
    if(username!=null) this.userService.getUser(username).subscribe(user=>{
      if(user.status==200){
        if(user.body) {
          this.user = user.body;
          this.user.favourites.forEach(f=>{f.date = new Date(f.date)
          })
        }
        
      }
      
    })
  }

  name = ""
  pages = 0

  updateBook(){
    this.bookService.updateBook(this.name, this.pages).subscribe(
      data=>{
        this.message = data.message
      }
    )
  }

  deleteBook(book: Book){
    this.bookService.deleteBook(book).subscribe(
      data=>{
        this.message = data.message
        this.bookService.getAll().subscribe(
          data=>this.allBooks = data
        )
      }
    )
  }

  addToFavourites(book: Book){
    let user = localStorage.getItem("loggedUser");
    if(user==null) return;

    else{
      this.userService.addToFavourites(user, book).subscribe(
        data=>{
          this.message = data.message;
        }
      );
    }
  }

  deleteFavourite(book:string){
    this.userService.deleteFromFav(this.user.username, book).subscribe(msg=>{
      this.message = msg.message
    })
  }

  updateFavourite(book:string){
    this.userService.updateFavourites(this.user.username, book).subscribe(msg=>{
      this.message = msg.message
    })
  }
  
}
