import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import {Need} from '../../models/Need';
import {CupboardService} from '../../services/cupboard.service';
import { UsersService } from '../../services/users.service';
import { userType } from '../../models/User';
@Component({
  selector: 'app-need-list',
  standalone: false,
  templateUrl: './need-list.component.html',
  styleUrl: './need-list.component.css'
})
export class NeedListComponent {
  needs: Need[] = [];
  searchResults: Need[] = [];

  constructor(
    private cupboardService: CupboardService,
    private usersService: UsersService
  ) {}

    refresh() {
        this.cupboardService.getNeeds().subscribe(n => {
          this.needs = n;
          this.searchResults = this.needs;
        });
        
        console.log(this.searchResults);
    }

  ngOnInit(): void {
    this.refresh()
     this.close();
  }

  private showElement(element: any) {
    if (element){
      element.style.visibility = 'visible';
      element.style.position = 'relative';
    }
  }

  private hideElement(element: any) {
    if (element){
      element.style.visibility = 'hidden';
      element.style.position = 'absolute';
    }
  }

  open() {
    this.hideElement(document.getElementById('search-button'));
    this.showElement(document.getElementById('search-container'));
  }

  close() {
    this.hideElement(document.getElementById('search-container'));
    this.showElement(document.getElementById('search-button'));
    this.hideElement(document.getElementById('search-status'));
  }

  private searchDelay: any;

  async search(form: any) {
    //wait .25 seconds before searching but cancel if another search is made during the wait to prevent too many api calls

    //remove previous search if it exists
    if (this.searchDelay) {
      clearTimeout(this.searchDelay);
    }
    if (form) {
      this.searchDelay = setTimeout(() => {
        
        if (form) {
          const currentSearchValue = form.search; //latest value of the search
          this.cupboardService.searchNeeds(currentSearchValue).subscribe((n) => {
            this.searchResults = n;
            console.log(currentSearchValue, this.searchResults);
            this.showElement(document.getElementById('search-results'));
            this.showElement(document.getElementById('search-status'));
            });
          }
        }, 250);
      } else {
        //user has cleared the search bar, we can skip the timeout for a 1/4 second faster response
        //clear timeout to stop pending search
        clearTimeout(this.searchDelay);
        this.searchResults = this.needs;
      }
      

     
  }

  delete(id : number) {
    this.cupboardService.deleteNeed(id).subscribe(() => {
      this.needs = this.needs.filter(n => n.id !== id)
    })
  }

  isManager() {
    const type = this.usersService.getCurrentUser()?.type;
    return type === ("MANAGER" as unknown as userType);
  }

  isHelper() {
    const type = this.usersService.getCurrentUser()?.type;
    return type === ("HELPER" as unknown as userType);
  }

  add(need: Need) {
    const currentUser = this.usersService.getCurrentUser();
    //console.log("get current user in angular:", currentUser)
    if (currentUser) {
      if (!currentUser.basket.includes(need.id)) {
        currentUser.basket.push(need.id);
        this.usersService.updateUser(currentUser).subscribe(() => {
          this.usersService.refreshBasket();
          error: (err: any) => {
            console.error(err);
          }
        });
      } else {
        window.alert("This need is already in your basket!")
      }
      

    }

  }

  back() {
    this.searchResults = this.needs;
  }
}