import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Task } from './task';
import { TaskService } from './task.service';

@Component({
  selector: 'my-tasks',
  templateUrl: './tasks.component.html'
})

export class TasksComponent implements OnInit {
  tasks: Task[][];
  selectedTask: Task;

  prevTasksInProgressLength: number;

  constructor(private router: Router, private taskService: TaskService) 


  getTasks(): void {
    this.taskService.getTasksByStatus(1).then(tasks => { this.tasks[1] = tasks; });
    this.taskService.getTasksByStatus(2).then(tasks => { this.tasks[2] = tasks; });
    this.taskService.getTasksByStatus(3).then(tasks => this.tasks[3] = tasks);
  }

  add(title: string, description: string, priority: number): void {
    title = title.trim();
    description = description.trim();
    if (!title || !description || priority > 3 || priority < 1) { return; }
    this.taskService.create(title, description, priority)
      .then(task => {
        this.tasks[1].push(task);
        this.selectedTask = null;
      });
  }

  delete(task: Task): void {
    this.taskService
      .delete(task.id)
      .then(() => {
        this.tasks[task.status] = this.tasks[task.status].filter(h => h !== task);
        if (this.selectedTask === task) { this.selectedTask = null; }
      });
  }  

  ngOnInit(): void {
    this.tasks = new Array<Task[]>();
    this.getTasks();
  }

  onSelect(task: Task): void {
    this.selectedTask = task;
  }

  gotoDetail(): void {
    this.router.navigate(['/detail', this.selectedTask.id]);
  }

  addTo($event: any, zone:number): void {
    console.log(zone);
    let droppedTask: Task = $event.dragData;
    var status = droppedTask.status;
    var index = this.tasks[status].indexOf(droppedTask);
    droppedTask.status = zone;

    this.taskService.update(droppedTask)
      .then(() => {
        this.tasks[status].splice(index, 1);
        this.tasks[zone].push(droppedTask);
      });
  }
}

{ }