import { AfterViewInit, Component, ElementRef, EventEmitter, HostListener, Input, Output, QueryList, ViewChild, ViewChildren } from '@angular/core';
import {CdkDragDrop, CdkDragEnd,moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';
import { SignatureForm } from 'src/app/modules/signataireForm';
import { Constant } from 'src/app/helper/constant';
import { Demande } from 'src/app/modules/demande';
import { UserPosition } from 'src/app/modules/userPosition';
import { Destinataire } from 'src/app/modules/destinataire';
import { DemandeService } from 'src/app/services/demande.service';
import { PdfService } from 'src/app/services/pdf.service';
import { ApiService } from 'src/app/services/api.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { Object } from 'src/app/modules/object';
import Konva from 'konva';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements AfterViewInit{

  pdfSrc = "https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf";

  @Input() signataireForm : SignatureForm = new SignatureForm() ;
  @Output() changerStatut: EventEmitter<void> = new EventEmitter<void>();

  @ViewChildren('drops') divs!: QueryList<ElementRef>;
  @ViewChildren('drags') drags!: QueryList<ElementRef>;

  page = 1;

  signataires : UserPosition[] = [];
  documents : Document[] = [];
  indexSelected! : number;
  spinner = false;

  constant : Constant= new Constant();
  demande : Demande = new Demande();
 
  screenWidth!: number;
  screenHeight!: number;
  paginationIndex = 1 ;
  paginationTotal = 0 ;
  destinataireSelected = new Destinataire();

  origin : Object [] = [
    {title: 'Signature', type:'file', src : '/assets/img/pen_sm.svg', text : "" , selected: false,width : 200, height : 100,transform :"", x : 0, y: 0 },
    {title: 'Cachet', type:'select', src : '/assets/img/cachet.svg', text : "" ,selected: false,width : 200, height : 100, transform :"", x : 0, y: 0},
    {title: 'Nom et prénom', type:'text' , src : '/assets/img/user.svg',text : "", selected: false,width : 200, height : 100, transform :"", x : 0, y: 0},
    {title: 'Date de signature', type:'date', src : '/assets/img/calendar.svg', text : "" , selected: false,width : 200, height : 100, transform :"", x : 0, y: 0},
    {title: 'Bouton de validation', type:'checked', src : '/assets/img/checked.svg',text : "", selected: false,width : 200, height : 100, transform :"", x : 0, y: 0},
  ];

  origin1 : Object [] = [
    {title: 'Signature', type:'file', src : '/assets/img/pen_sm.svg', text : "" , selected: false,width : 200, height : 100,transform :"", x : 0, y: 0 },
    {title: 'Cachet', type:'select', src : '/assets/img/cachet.svg', text : "" ,selected: false,width : 100, height : 100, transform :"", x : 0, y: 0},
    {title: 'Nom et prénom', type:'text' , src : '/assets/img/user.svg',text : "", selected: false,width : 200, height : 50, transform :"", x : 0, y: 0},
    {title: 'Date de signature', type:'date', src : '/assets/img/calendar.svg', text : "" , selected: false,width : 200, height : 50, transform :"", x : 0, y: 0},
    {title: 'Bouton de validation', type:'checked', src : '/assets/img/checked.svg',text : "", selected: false,width : 200, height : 100, transform :"", x : 0, y: 0},
  ];
  width = 200;
  height = 200;
  select : Object = new Object();

  indexUser = 0;

  itemdeleted : any;
  indexPage = 0;
  pdfFile: File | null = null;
  images: string[] = [];
  objects : Object[] = [];
  style!: { position: string; left: string; top: string; width: string; height: string; };
  isVisible = false;
  transformMatrix: string | undefined;
  canView = false;
  selectedRect: Konva.Rect | null = null;

  constructor(private pdfToImageService: PdfService, private apiService: ApiService,
    private demandeService: DemandeService, private router: Router, private message: NzMessageService, private spinnerTemplate: NgxSpinnerService
  ) {
    console.log(this.signataireForm)
    this.screenWidth = window.innerWidth;
    this.screenHeight = window.innerHeight;
   }

   @ViewChild('stage', { static: false }) stageRef!: ElementRef;

  stage!: Konva.Stage;
  layer!: Konva.Layer;
  layerText!: Konva.Layer;
  rectangles: Konva.Rect[] = [];

  ngOnInit(): void {
    this.images.push(this.constant.data)

    this.destinataireSelected = this.signataireForm.demande.destinataires[0];


  
  }

  ngAfterViewInit() {
    console.log(this.stageRef)
    this.stage = new Konva.Stage({
      container: "container",
      width: 793,
      height: 841
    });

    this.layer = new Konva.Layer();
    this.layerText = new Konva.Layer();
    this.stage.add(this.layer);
    this.stage.add(this.layerText);

    this.layer.on('dragmove', () => {
      this.layerText.children.forEach(text => {
        const rectId = text.getAttr('rectId');
        console.log(rectId)
        const rectangle = this.layer.findOne('#' + rectId);
        console.log(rectangle)
        if (rectangle) {
          text.position({
            x: rectangle.x(),
            y: rectangle.y() + rectangle.height()*0.30 // Ajustez la position verticale du texte si nécessaire
          });
        }
      });
    });
  }
  
  addRectang2le(event: CdkDragEnd, id : string, obejt: Object) {

    const groupe = new Konva.Group({
      x: event.dropPoint.x/3,
      y: event.dropPoint.y/3,
    });


    console.log(event)
    const rect = new Konva.Rect({
      width: 200,
      height: 100,
      fill: "#ffd65bb7",
      stroke: "green",
      strokeWidth: 3,
      draggable: true,
      name: obejt.title,
      id: id
    });

    groupe.add(rect);

    Konva.Image.fromURL("/assets/img/pen_sm.svg", (image: any) => {
      // Positionner l'image SVG
      image.position({
        x: groupe.x(), // Centrer horizontalement dans le rectangle
        y: groupe.y()  // Centrer verticalement dans le rectangle
      });
      // Ajouter l'image SVG au groupe
      groupe.add(image);
      // Rafraîchir la scène
      this.layer.batchDraw();
    });

    this.layer.add(groupe); 

    rect.on('dragend', () => {
      console.log('Rectangle resized: x : ', rect.x(), ' y : ', rect.y());
    });

    rect.on('click', () => {
      console.log('Rectangle id : ', rect.stroke());
 
      rect.strokeWidth(10);
      this.layer.batchDraw();
    });

  
    this.rectangles.push(rect);
    this.layer.draw();
  }

  ajouterTitre(layer: any, rect: any) {
    const text = new Konva.Text({
      x: rect.x() , // Position x correspondant au rectangle
      y: rect.y() + rect.height()*0.30, // Position y correspondant au rectangle
      text: rect.name(),
      fontSize: 20,
      align: 'center',
      fill: 'black',
       width: rect.width()
    });
    text.setAttr('rectId', rect.id());
    layer.add(text);
    layer.draw();
  }

  resizeRectangle(rect: Konva.Rect, newWidth: number, newHeight: number) {
    rect.width(newWidth);
    rect.height(newHeight);
    this.layer.draw();
  }

  selectRectangle(rect: Konva.Rect) {
    console.log("Meeee")
    rect.fill('red');
    this.layer.batchDraw();
  }


  
 


 
   executerMethodeParent() {
     // Exécutez votre méthode ici
     this.changerStatut.emit();
   }

   testMe(event: CdkDragEnd, index:number){

    this.addRectangle(event, index.toString(),this.origin1[index])
      console.log(event)
      console.log(event.source.getFreeDragPosition());
      var obj = event.source.dropContainer.data[index];
      const draggedElement = event.source.element.nativeElement;
      // console.log(draggedElement);
      const boundingRect = draggedElement.getBoundingClientRect();
      obj.transform = "matrix(1, 0, 0, 1, "+boundingRect.left/2+", "+boundingRect.top/2+")";
      console.log(draggedElement);
      this.objects.push(obj);
  }

   nextPage(pageIndex: number) {
    this.paginationIndex = pageIndex;
    this.indexPage = pageIndex - 1;
  }




  selected(num:number){
    this.select = this.origin[num];
   // console.log(this.origin[num]);
   
  }



  addRectangle(event: CdkDragEnd, id : string, obejt: Object) {

    const groupe = new Konva.Group({
      x: event.dropPoint.x/3,
      y: event.dropPoint.y/3,
    });
    const rect = new Konva.Rect({
      x: event.dropPoint.x/3,
      y: event.dropPoint.y/3,
      width: obejt.width,
      height: obejt.height,
      fill: "#ffd65bb7",
      stroke: "green",
      strokeWidth: 5,
      draggable: true,
      name: obejt.title,
      id: id
    });
    this.layer.add(rect); 
    this.ajouterTitre(this.layerText, rect);
    rect.on('dragend', () => {
      console.log(rect)
      console.log('Rectangle resized: x : ', rect.x(), ' y : ', rect.y());

    });
    rect.on('click', () => {
      console.log('Rectangle id : ', rect.id());
     
      this.layer.batchDraw();
    });
    this.rectangles.push(rect);
    this.layer.draw();
  }



}
