import { Component, OnInit } from '@angular/core';
import { FriendsService } from '../../services/friends/friends.service';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-friend-page',
  imports: [CommonModule],
  templateUrl: './friend-page.component.html',
  styleUrls: ['./friend-page.component.css']
})
export class FriendPageComponent implements OnInit {
  protected listFriend: {username: string, status: string, friend_user_id: string, id: string}[] = [];
  userId: string = "";
  status: string = "";
  isFriendModalOpen: boolean = false;
  hasAcceptedFriends: boolean = false ;
  hasPendingFriends: boolean = false;


  constructor(private friendService: FriendsService) {
  }

  ngOnInit(): void {
    this.getFriendData();
  }

  private getFriendData(): void {
    this.friendService.getFriend().subscribe((data: any[]) => {
      if (data.length > 0) {
        data.forEach(friend => {
          console.log(friend)
          let status = friend['status'];
          let userId = friend['friend_user_id'];
          let id = friend['id'];
          this.friendService.getFriendById(userId).subscribe((friendData: any) => {
            this.listFriend.push({
              username: friendData.username,
              status: status,
              friend_user_id: userId,
              id: id
            });
          });
        });
      }
    });
  }

  onAcceptOrDeny(id: string, choice: string){
    if (choice == "accept"){
      // If return code is 200, then the friend has been accepted so we can change the status of the friend to accepted
      this.friendService.acceptFriendById(id).subscribe((data: any) => {
        if (data.message == "Friend request accepted"){
          this.listFriend.forEach(friend => {
            if (friend.id == id){
              friend.status = "accepted";
            }
          });
        }
      });
    } else {
      // If return code is 200, then the friend has been denied so we can delete the friend from the list
      this.friendService.denyFriendById(id).subscribe((data: any) => {
        if (data.message == "Friend request denied"){
          this.listFriend.forEach((friend, index) => {
            if (friend.id == id){
              this.listFriend.splice(index, 1);
            }
          });
        }
      });
    }
  }
  
  openFriendModal() {
    this.isFriendModalOpen = true;
  }

  closeFriendModal() {
    this.isFriendModalOpen = false;
  }

  deleteFriend(id: string){
    this.friendService.deleteFriend(id).subscribe();
  }
}
