import {
  Component,
  HostBinding,
  Input,
  OnDestroy,
  OnInit,
  ViewEncapsulation,
  Output,
  EventEmitter
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil, take } from 'rxjs/operators';
import { Dashboard } from 'src/modules/dashboard/model/Dashboard';
import { DashboardService } from 'src/modules/dashboard/service/dashboard.service';

@Component({
  selector: 'app-pages-settings-dashboard-list-item',
  templateUrl: './list-item.component.html',
  styleUrls: ['./list-item.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ListItemComponent implements OnInit, OnDestroy {
  tags: any[];

  @Input()
  dashboard: Dashboard;

  @Output()
  deleted: EventEmitter<number> = new EventEmitter<number>();

  @HostBinding('class.selected')
  selected: boolean;

  @HostBinding('class.completed')
  completed: boolean;

  @HostBinding('class.move-disabled')
  moveDisabled: boolean;

  // Private
  private _unsubscribeAll: Subject<any>;

  /**
   * Constructor
   *
   * @param {TodoService} _todoService
   * @param {ActivatedRoute} _activatedRoute
   */
  constructor(
    private _activatedRoute: ActivatedRoute,
    private dashboardService: DashboardService
  ) {
    // Disable move if path is not /all
    // if (_activatedRoute.snapshot.url[0].path !== 'all') {
    //   this.moveDisabled = true;
    // }

    // Set the private defaults
    this._unsubscribeAll = new Subject();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Set the initial values
    //this.completed = this.todo.completed;
  }

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next();
    this._unsubscribeAll.complete();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * On selected change
   */
  onSelectedChange(): void {}

  /**
   * Toggle display
   */
  toggleDisplay(event): void {
    event.stopPropagation();

    this.dashboardService
      .updateDashboardDisplay(this.dashboard.id, !this.dashboard.display)
      .pipe(take(1))
      .subscribe(
        res => {
          this.dashboard = res;
        },
        err => {}
      );
  }

  /**
   * Toggle star
   */
  removeDashboard(event): void {
    event.stopPropagation();

    this.dashboardService
      .deleteDashboard(this.dashboard.id)
      .pipe(take(1))
      .subscribe(
        () => {
          this.deleted.emit(this.dashboard.id);
        },
        err => {}
      );
  }
}
