import {Component, OnInit} from '@angular/core';
import {ForgottenActivityRequest, ScheduleService, TaskService, TaskShortInfo} from "../../../api";
import {MatSnackBar} from "@angular/material/snack-bar";
import {DialogRef} from "@angular/cdk/dialog";
import {MatDialogRef} from "@angular/material/dialog";
import {filter, map, Observable, startWith} from "rxjs";
import {FormControl} from "@angular/forms";

@Component({
  selector: 'app-forgotten-task-start-dialog',
  templateUrl: './forgotten-task-start-dialog.component.html',
  styleUrls: ['./forgotten-task-start-dialog.component.css']
})
export class ForgottenTaskStartDialogComponent implements OnInit{

  tasks: TaskShortInfo[] = []
  myControl: FormControl = new FormControl('');
  filteredOptions: Observable<string[]> | undefined;

  lastSchedule: boolean = false
  plannedSchedule: boolean = false
  minutesSpentControl: FormControl = new FormControl();


  constructor(private taskService: TaskService,
              private snackbar: MatSnackBar,
              private dialogRef: MatDialogRef<ForgottenTaskStartDialogComponent>,
              private scheduleService: ScheduleService) {
  }

  ngOnInit() {
    this.taskService.tasksAllScopeDetailedGet("UNFINISHED", false).subscribe({
      next: resp => {
        this.tasks = resp;
        this.filteredOptions = this.myControl.valueChanges.pipe(
          startWith(''),
          map(value => this._filter(value || '')),
        );
      },
      error: err =>  {
        this.snackbar.open("Unexpected error", "", {duration: 2000});
      }
    })
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.tasks.map(x => x.taskName).filter(option => option.toLowerCase().includes(filterValue))
  }

  registerActivity() {
    const task = this.tasks.find(task => task.taskName === this.myControl.value);
    if(task != undefined) {
      /*this.scheduleService.schedulesTaskIDForgottenPost(task.taskID, {
        mode: this.determineRegisterMode(),
        minutesSpent: this.minutesSpentControl.value
      }).subscribe({
        next: resp => {
          this.dialogRef.close(resp);
        },
        error: err => {
          if(err.status == 400) {
            this.snackbar.open("Invalid Operation", "", {duration: 2000});
          } else if(err.status == 403) {
            this.snackbar.open("No permission", "", {duration: 2000});
          } else if(err.status == 404) {
            this.snackbar.open("Task not found", "", {duration: 2000});
          } else {
            this.snackbar.open("Unexpected error", "", {duration: 2000});
          }
        }
      })*/
    }
  }
}