import { AfterViewInit, Component, ElementRef, EventEmitter, Input, NgZone, OnInit, Output, ViewChild } from '@angular/core';
import Utils from 'src/app/lib/filler/common/utils';
import Editor from 'src/app/lib/filler/core/editor';
import ImageLayer from 'src/app/lib/filler/core/image-layer';
import { EditorDirective } from 'src/app/lib/filler/editor.directive';

const TAG = 'ColorPickerComponent';

@Component({
  selector: 'art-color-picker',
  template: `
  <div #resizeBox class="wraper" cdkDrag (click)="log()" >
    <div #dragHandleRight class="resize-handle right" cdkDragLockAxis="x" data-axis="x" (cdkDragMoved)="dragMove(dragHandleRight)"  cdkDrag ></div>
    <div #dragHandleBottom class="resize-handle bottom" cdkDragLockAxis="y" data-axis="y" (cdkDragMoved)="dragMove(dragHandleBottom)" cdkDrag ></div>
    <div #dragHandleCorner class="resize-handle corner"  (cdkDragMoved)="dragMove(dragHandleCorner)" cdkDrag  ></div>

    <canvas appEditor ></canvas>
    <div class="drag-handle " cdkDragHandle  >

      <div class="left">
        <button class="btn btn-sm" (click)="file.click()">
          <i class="fal fa-plus" ></i> 
        </button>
        <input #file type="file" style="display:none;" (change)="selectFile($event)" />
      </div>
      <div class="right">
        <!--
        <button class="btn btn-sm" (click)="collapse()">
          <i class="fal fa-minus" ></i> 
        </button>
        <button class="btn btn-sm" (click)="expand()">
          <i class="fal fa-expand" ></i> 
        </button>
        -->
        <button class="btn btn-sm" (click)="onClose.emit()">
          <i class="fal fa-times" ></i> 
        </button>
      </div>
    </div>

  </div>
  `,
  styles: [
    `
    :host{
      position:fixed;
      z-index:0;
      left:0;
      top:0;
      right:0;
      bottom:0;
      pointer-events:none;
      background-color: transparent;
    }

    .wraper{
      box-sizing:border-box;
      position:absolute;
      z-index:10;
      pointer-events:auto;
      border:0px solid #ccc;
      transition: box-shadow 200ms cubic-bezier(0, 0, 0.2, 1);
      box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2),
                  0 2px 2px 0 rgba(0, 0, 0, 0.14),
                  0 1px 5px 0 rgba(0, 0, 0, 0.12);
    }

    .wraper:active{
      box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
              0 8px 10px 1px rgba(0, 0, 0, 0.14),
              0 3px 14px 2px rgba(0, 0, 0, 0.12);
    }


    .drag-handle{
      position:absolute;
      z-index : 100;
      left:0;
      top:0; 
      right:0;
      background-color:#fff;
      //border-bottom:1px solid #ccc;
      cursor : move;
      box-shadow: 0 1px 5px rgba(0, 0,0, 0.2);

      display:flex;
      flex-direction: row;
      align-items: center; 
      justify-content:flex-end;
    }

    .drag-handle .left {
      flex:1;
    }

    .drag-handle .right{
      display:flex;
      flex-direction: row;
      align-items: center; 
      justify-content:flex-end;
    }

    canvas {
      width:100%;
      height:100%;
      background-color:yellow;
    }

    .resize-handle {
      position: absolute;
      background-color: transparent;
      top:0; 
      left:0;
    }

    .resize-handle.corner {
      width: 15px;
      height: 15px;
      cursor: nwse-resize;
    }

    .resize-handle.right {
      width: 2px;
      height: 100%;
      cursor: ew-resize;
    }

    .resize-handle.bottom {
      height: 2px;
      width: 100%;
      cursor: ns-resize;
    }


    .btn{
      border:none;
    }

    .btn i{
      margin:none;
    }

    
    `
  ]
})
export class ColorPickerComponent implements OnInit, AfterViewInit {

  @Output() onPickColor = new EventEmitter<any>();

  @Output() onClose = new EventEmitter<any>();

  @ViewChild('resizeBox') resizeBox: ElementRef;
  @ViewChild('dragHandleCorner') dragHandleCorner: ElementRef;
  @ViewChild('dragHandleRight') dragHandleRight: ElementRef;
  @ViewChild('dragHandleBottom') dragHandleBottom: ElementRef;

  get resizeBoxElement(): HTMLElement { return this.resizeBox.nativeElement; }
  get dragHandleCornerElement(): HTMLElement { return this.dragHandleCorner.nativeElement; }
  get dragHandleRightElement(): HTMLElement { return this.dragHandleRight.nativeElement; }
  get dragHandleBottomElement(): HTMLElement { return this.dragHandleBottom.nativeElement; }



  readonly initialWidth: number = 300;
  readonly initialHeight: number = 300;

  expandHeight = this.initialHeight;


  private _image: HTMLImageElement;
  public get image(): HTMLImageElement {
    return this._image;
  }
  @Input()
  public set image(value: HTMLImageElement) {
    this._image = value;
    this.init();
  }

  imageLayer: ImageLayer;


  @ViewChild(EditorDirective) editorRef: EditorDirective;


  constructor(private ngZone: NgZone) { }



  expand() {
    this.resizeBoxElement.style.height = `${this.expandHeight}px`;
    this.editorRef.editor.updateCanvas();
    this.setAllHandleTransform();
  }

  collapse() {
    this.expandHeight = parseInt(this.resizeBoxElement.style.height);
    this.resizeBoxElement.style.height = "40px";
    this.editorRef.editor.updateCanvas();
    this.setAllHandleTransform();
  }


  async selectFile(event) {
    let files = (<HTMLInputElement>event.target).files;
    if (files.length <= 0) return;
    this.image = await Utils.blobToImage(files[0]);
  }


  ngAfterViewInit(): void {
    console.log(TAG, 'editorRef:', this.editorRef);
    this.editorRef.editor.padding = { left: 0, top: 0, right: 0, bottom: 0 };
    this.editorRef.editor.on('pick-color', (editor: Editor, color: string) => {
      this.onPickColor.emit(color);
    })
    this.init();

    this.resizeBoxElement.style.width = `${this.initialWidth}px`;
    this.resizeBoxElement.style.height = `${this.initialHeight}px`;
    let parentRect = this.resizeBoxElement.parentElement.getBoundingClientRect();
    let boxRect = this.resizeBoxElement.getBoundingClientRect();
    let left = parentRect.right - boxRect.width - 10;
    let top = 10;
    this.resizeBoxElement.style.left = `${left}px`;
    this.resizeBoxElement.style.top = `${top}px`;

    this.setAllHandleTransform();
  }

  init() {
    console.log('init, editor=', this.editorRef);
    if (!this.image) return;
    if (!this.imageLayer) {
      this.imageLayer = new ImageLayer(this.image);
    } else {
      this.imageLayer.image = this.image;
    }
    this.editorRef?.editor.setBackgroundLayer(this.imageLayer);
    this.editorRef?.editor.ready.then(() => {
      this.editorRef.editor.bestFit();
    })
  }

  ngOnInit(): void {
  }





  setAllHandleTransform() {
    const rect = this.resizeBoxElement.getBoundingClientRect();
    this.setHandleTransform(this.dragHandleCornerElement, rect, 'both');
    this.setHandleTransform(this.dragHandleRightElement, rect, 'x');
    this.setHandleTransform(this.dragHandleBottomElement, rect, 'y');
  }

  setHandleTransform(
    dragHandle: HTMLElement,
    targetRect: ClientRect | DOMRect,
    position: 'x' | 'y' | 'both'
  ) {
    const dragRect = dragHandle.getBoundingClientRect();
    const translateX = targetRect.width - dragRect.width;
    const translateY = targetRect.height - dragRect.height;

    if (position === 'x') {
      dragHandle.style.transform = `translate(${translateX}px, 0)`;
    }

    if (position === 'y') {
      dragHandle.style.transform = `translate(0, ${translateY}px)`;
    }

    if (position === 'both') {
      dragHandle.style.transform = `translate(${translateX}px, ${translateY}px)`;
    }
  }

  //dragMove(dragHandle: HTMLElement, $event: CdkDragMove<any>) {
  dragMove(dragHandle: HTMLElement,) {
    this.ngZone.runOutsideAngular(() => {
      this.resize(dragHandle, this.resizeBoxElement);
    });
    this.log();
  }

  log() {
    console.log('resizeBox:', this.resizeBoxElement.getBoundingClientRect());
    console.log('rightHandle:', this.dragHandleRightElement.getBoundingClientRect());
    console.log('bottomHandle:', this.dragHandleBottomElement.getBoundingClientRect());
  }

  resize(dragHandle: HTMLElement, target: HTMLElement) {
    const dragRect = dragHandle.getBoundingClientRect();
    const targetRect = target.getBoundingClientRect();

    console.log('color', dragRect.top, targetRect.top, dragRect.height);

    const width = dragRect.left - targetRect.left + dragRect.width;
    const height = dragRect.top - targetRect.top + dragRect.height;


    target.style.width = width + 'px';
    target.style.height = height + 'px';

    this.editorRef.editor.updateCanvas();

    this.setAllHandleTransform();
  }

}
