import { ChangeDetectionStrategy, Component } from '@angular/core';
import { TaskService } from 'src/app/services/task.service';
import { Task } from 'src/app/models/task';
import { ActivatedRoute, Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { ViewWillEnter } from '@ionic/angular';

@Component({
  selector: 'app-tasks',
  templateUrl: 'tasks.page.html',
  styleUrls: ['tasks.page.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class TasksPage implements ViewWillEnter {
  public tasks$: BehaviorSubject<Array<Task>> = new BehaviorSubject<Array<Task>>([]);
  public usernames = ['', 'See', 'Huffle']

  constructor(
    private taskService: TaskService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.getTasks();
  }

  ionViewWillEnter(): void {
    this.getTasks();
  }

  getTasks() {
    setTimeout(() => {
      this.taskService.getTaskList().subscribe(tasks => {
        this.tasks$.next(tasks);
      });
    }, 100);
  }

  createTask() {
    this.router.navigate(['add'], { relativeTo: this.route });
  }

  updateTask(id: number) {
    this.router.navigate(['edit', id], { relativeTo: this.route });
  }

  completeTask(id: number) {
    this.taskService.completeTask(id);
    this.getTasks();
  }
}
