import {Component, EventEmitter, Input, Output} from '@angular/core';

@Component({
  selector: 'app-courseware-folder-table',
  templateUrl: './courseware-folder-table.component.html',
  styleUrls  : ['./courseware-folder-table.component.scss']
})
export class CoursewareFolderTableComponent {
  @Input() data = [];
  @Input() isInLinkFolder = false;

  @Output() handleSelect = new EventEmitter();
  @Output() enterFolder = new EventEmitter();
  @Output() enterCourseware = new EventEmitter();
  @Output() updateName = new EventEmitter();
  @Output() confirmFolderName = new EventEmitter();
  @Output() confirmCoursewareName = new EventEmitter();
  @Output() moveByDrag = new EventEmitter();
  @Output() handleSort = new EventEmitter();

  constructor() {
    // console.log(this.data);
  }

  onHandleChecked(item) {
    this.handleSelect.emit(item);
  }

  dbClickFolder(item) {
    this.enterFolder.emit(item);
  }

  dbClickFile(item) {
    this.enterCourseware.emit(item);
  }

  onUpdateName(item) {
    if (this.isInLinkFolder) {
      return;
    }
    item._name = item.name;
    item._inEdit = true;
    this.updateName.emit(item);
  }

  onConfirmFolderName(item) {
    this.confirmFolderName.emit(item);
  }

  onConfirmCoursewareName(item) {
    this.confirmCoursewareName.emit(item);
  }

  sort(sort: { key: string, value: string }): void {
    const { key, value } = sort;
    // remove value suffix 'end', origin value ['descend', 'ascend']
    const t = value ? value.substr(0, value.length - 3) : value;
    this.handleSort.emit({ key, value: t });
  }

  onHandleDragStart(ev, item) {
    if (this.isInLinkFolder) {
      return;
    }
    ev.dataTransfer.setData('sid', item.sid);
    ev.dataTransfer.setData('type', item.type);
  }

  dragOverHandler(ev, item) {
    if (this.isInLinkFolder) {
      return;
    }
    ev.preventDefault();
    ev.dataTransfer.dropEffect = 'move';
    ev.currentTarget.style.background = '#d4d4d4';
  }
  dragLeaveHandler(ev) {
    if (this.isInLinkFolder) {
      return;
    }
    ev.preventDefault();
    ev.currentTarget.style.background = '';
  }

  dropFolderHandler(ev, item) {
    if (this.isInLinkFolder) {
      return;
    }
    ev.preventDefault();
    ev.currentTarget.style.background = '';
    const sid = ev.dataTransfer.getData('sid');
    const type = ev.dataTransfer.getData('type');
    const object = { sid, type, item };
    this.moveByDrag.emit(object);
  }
}
