import { Component, ElementRef, HostListener, Input, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { SignatureForm } from 'src/app/modules/signataireForm';
import { PdfService } from 'src/app/services/pdf.service';
import { Object } from 'src/app/modules/object';
import { Document } from 'src/app/modules/document';
import SignaturePad from "signature_pad";
import { Demande } from 'src/app/modules/demande';
import { UserPosition } from 'src/app/modules/userPosition';
import { ApiService } from 'src/app/services/api.service';
import { DemandeService } from 'src/app/services/demande.service';
import { Position } from 'src/app/modules/position';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SignaturePage } from 'src/app/modules/signaturePage';
import { ObjetSignature } from 'src/app/modules/objetSignature';
import { NgxSpinnerService } from 'ngx-spinner';
import Konva from 'konva';
import { Constant } from 'src/app/helper/constant';

@Component({
  selector: 'app-signer-document',
  templateUrl: './signer-document.component.html',
  styleUrls: ['./signer-document.component.scss']
})
export class SignerDocumentComponent {
  pdfSrc = "../../assets/test.pdf";
  files_list_signatures: any[] = [];
  files_list: any[] = [];
  cahets_list: any[] = [];
  signatures_listBase64: any[] = [];
  @Input() key!: string;
  @ViewChild("canvas", { static: true }) canvas: ElementRef | undefined;

  signaturePage: SignaturePage[] = [];

  next = false;
  spinner = false;

  demande: Demande = new Demande();

  obejcts: any[] = [];
  documents: Document[] = [];
  indexSelected!: number;

  screenWidth!: number;
  screenHeight!: number;
  paginationIndex = 1;
  paginationTotal = 0;

  origin: Object[] = [
    {
      title: 'Signature', type: 'file', src: '../../../assets/img/pen_sm.svg', text: "", selected: false, width: 200, height: 100, transform: "matrix(1, 0, 0, 1, 303, 943)", x: 700,
      y: 1000
    },
  ];
  width = 200;
  height = 200;
  select: Object = new Object();
  hide = false;

  itemdeleted: any;
  indexPage = 0;
  pdfFile: File | null = null;
  images: string[] = [];
  style!: { position: string; left: string; top: string; width: string; height: string; };
  isVisible: boolean = false;
  isVisiblecachets: boolean = false;
  group: any;
  groupCachet: any;

  stage!: Konva.Stage;
  layer!: Konva.Layer;
  layerText!: Konva.Layer;
  signed = false;
  signatures: SignaturePage[] = [];

  constructor(private pdfToImageService: PdfService, private elementRef: ElementRef, private demandeService: DemandeService, private apiService: ApiService,
    private message: NzMessageService, private spinnerTemplate: NgxSpinnerService
  ) {
    console.log(this.key)
    this.screenWidth = window.innerWidth;
    this.screenHeight = window.innerHeight;
    console.log('Largeur de l\'écran:', this.screenWidth);
    console.log('Hauteur de l\'écran:', this.screenHeight);
  }
  ngOnInit(): void {
    console.log(this.key)
    this.getDemande();
  }

  showModal(rect: any): void {
    this.rectangleSelected = rect;
    this.isVisible = true;
  }
  rectangleSelected: any;
  showModalCachet(rect: any): void {
    this.rectangleSelected = rect;
    console.log(this.rectangleSelected)
    this.isVisiblecachets = true;
  }

  getImage(src: string) {
    if (src != "") {
      console.log(src);
      this.signatures_listBase64.push(src);
      this.next = false;
    }
  }

  createMessage(type: string, messqge: string): void {
    this.message.create(type, messqge);
  }

  handleCancel(): void {
    this.isVisible = false;
    this.next = false;
  }

  convertfile(file: File, tab: any) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      const base64String: string = reader.result as string;
      tab.push(base64String);
    };
    reader.onerror = (error) => {
      console.error('Error occurred while reading the file:', error);
    };
  }

  handleCancelcachet(): void {
    this.isVisiblecachets = false;
  }

  nextPage(pageIndex: number) {
    var sign: SignaturePage = new SignaturePage()
    this.paginationIndex = pageIndex;
    this.indexPage = pageIndex - 1;
    sign.page = this.indexPage;
    this.changePage()
  }

  fileObserver($event: any) {
    console.log($event);
    this.files_list_signatures.push($event.target.files[0]);
    this.convertfile($event.target.files[0], this.signatures_listBase64);
    console.log(this.files_list_signatures)
  }

  fileObserverCachet($event: any) {
    console.log($event);
    this.files_list.push($event.target.files[0]);
    this.convertfile($event.target.files[0], this.cahets_list);
    console.log(this.files_list)
  }

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

  changeSrc(index: number) {
    if (index >= 0) {
      this.signed = true;
      this.modifierImage(this.signatures_listBase64[index], this.group, "Signature", this.rectangleSelected);
      this.signatures.forEach((sign: SignaturePage) => {
        if (sign.page == this.indexPage) {
          sign.objetSignatureDtos.forEach((data: ObjetSignature) => {
            if (data.typeObjet == "SIGNATURE") {
              data.fileBase64 =  this.signatures_listBase64[index];
            }
          })
        }
      })
    }
    this.isVisible = false;
  }

  changeSrcCachet(index: number) {
    if (index >= 0) {
      this.modifierImage(this.cahets_list[index], this.groupCachet, "Cachet", this.rectangleSelected)
      this.signatures.forEach((sign: SignaturePage) => {
        if (sign.page == this.indexPage) {
          sign.objetSignatureDtos.forEach((data: ObjetSignature) => {
            if (data.typeObjet == "CACHET") {
              data.fileBase64 = this.cahets_list[index];
            }
          })
        }
      })
    }
    this.isVisiblecachets = false;
  }

  destination: any[] = [
  ];

  isHovered = false;

  getFile(name: string) {
    this.apiService.getFile(name).subscribe(image => {
      console.log(image);
      this.convertPdfToImages(image);
    })
  }
  onFileSelected(event: any) {
    this.pdfFile = event.target.files[0];
  }

  changePage() {
    this.obejcts = [];
    this.supprimerTousRectangles(this.layer);
    this.supprimerTousText(this.layerText);
    this.demande.destinataires[0].positions.map((pos: Position, index: number) => {
      if (pos.information.page == this.indexPage) {
        if (index > 0) {
          this.demande.destinataires[0].positions[this.indexPage - 1].information.obejcts = this.obejcts;
        }
        this.obejcts = pos.information.objects;

      }
    })
    this.obejcts.map((element: any) => {
      if (element.name == "Signature" || element.name == "Cachet") {
        this.signatures.forEach((data: SignaturePage) => {
          if (data.page == this.indexPage) {
            console.log(data)
            data.objetSignatureDtos.forEach((obj: ObjetSignature) => {
              if (obj.typeObjet == "SIGNATURE" && element.name == "Signature") {
                element.fileBase64 = obj.fileBase64;
              }
              else if (obj.typeObjet == "CACHET" && element.name == "Cachet") {
                element.fileBase64 = obj.fileBase64;
              }
            })
          }
        })
      }
    })
    this.initializateObjects(this.obejcts);
  }

  getDemande() {
    this.demandeService.getDemandeToken(this.key).subscribe((data: any) => {
      if (data.status_code == "000") {
        this.demande = data.response_data;
        console.log(this.demande)
        this.getFile(this.demande.documents[0].directory);
        this.demande.destinataires[0].positions.forEach((pos: Position) => {
          let sign = new SignaturePage();
          sign.page = pos.information.page;
          pos.information.objects.forEach((element: any) => {
            var obejt = new ObjetSignature();
            if (element.name == "Signature" || element.name == "Cachet") {
              obejt.fileBase64 = "";
              obejt.height = element.height;
              obejt.width = element.width;
              obejt.x = element.x;
              obejt.y = element.y;
              if (element.name == "Signature") {
                obejt.typeObjet = "SIGNATURE";
              }
              else if (element.name == "Cachet") {
                obejt.typeObjet = "CACHET";
              }
            } else {
              var currentDate = new Date();
              var formattedDate = currentDate.toLocaleDateString('fr-FR', { year: 'numeric', month: '2-digit', day: '2-digit' });
              obejt.height = element.height;
              obejt.width = element.width;
              obejt.x = element.x;
              obejt.y = element.y;
              if (element.name == "Nom et prénom") {
                obejt.typeObjet = "NAME";
                obejt.text = this.demande.destinataires[0].name;
              }
              else {
                obejt.typeObjet = "DATE";
                obejt.text = formattedDate;
              }
            }
            sign.objetSignatureDtos.push(obejt);
          })
          this.signatures.push(sign);
          if (pos.information.page == this.indexPage) {
            this.obejcts = pos.information.objects;
          }
        })
        console.log(this.signatures)
        this.initializateObjects(this.obejcts);
      } else {
        this.hide = true;
        this.createMessage("info", data.status_label);
      }
    }, (error) => {
      this.createMessage("error", "Erreur survenue au moment de la récupération du document.");
    })
  }

  initializateObjects(dataObjects: any) {
    dataObjects.map((elment: any) => {
      elment.draggable = false;
      elment.fill = "white"
      if (elment.name == "Nom et prénom") {
        elment.strokeWidth = 0;
        elment.title = this.demande.destinataires[0].name;
        this.initialzeRectangle(elment);
      } else if (elment.name == "Date de signature") {
        elment.strokeWidth = 0;
        var currentDate = new Date();
        var formattedDate = currentDate.toLocaleDateString('fr-FR', { year: 'numeric', month: '2-digit', day: '2-digit' });
        elment.title = formattedDate;
        this.initialzeRectangle(elment);
      }
      else if (elment.name == "Signature") {
        if (!elment.fileBase64) {
          elment.strokeWidth = 1
          elment.fileBase64 = new Constant().dataIcon2
          this.initialzeImage(elment, true);
        } else {
          elment.strokeWidth = 0
          this.initialzeImage(elment, false);
        }
      } else if (elment.name == "Cachet") {
        if (!elment.fileBase64) {
          elment.strokeWidth = 1
          elment.fileBase64 = new Constant().dataIcon
          this.initialzeImage2(elment, true);
        } else {
          elment.strokeWidth = 0
          this.initialzeImage2(elment, false);
        }
      }
    })
  }

  async convertPdfToImages(file: File) {
    if (!file) {
      console.error('Aucun fichier PDF sélectionné.');
      return;
    }
    try {
      console.log("images")

      this.images = await this.pdfToImageService.convertToImage(file);
      this.paginationTotal = this.images.length
      this.images.forEach((item: any) => {
        let document: Document = new Document()
        // document.page = item;
        this.documents.push(document);
      })

    } catch (error) {
      console.error('Une erreur est survenue lors de la conversion du PDF en images:', error);
    }
  }

  signDocument() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
    this.spinnerTemplate.show();

    this.signatures.map((sign : SignaturePage) => {
        sign.objetSignatureDtos.forEach((obj : ObjetSignature) => {
          if(obj.fileBase64){
            obj.fileBase64 = obj.fileBase64.substring(obj.fileBase64.indexOf(',') + 1)
          }
        })
    })
    this.demandeService.modifyPdfToken(this.signatures, this.key).subscribe((data: any) => {
      this.spinnerTemplate.hide();
      if (data.status_code == "000") {
        this.createMessage('success', "Document signé.");
        window.location.reload();
      } else {
        this.createMessage('info', data.status_label)
      }
    }, error => {
      this.spinnerTemplate.hide();
      this.createMessage("error", "Erreur survenue au moment de la Signature du document. Veuillez réessayer.")
    })
    console.log(this.signaturePage);
  }

  initialzeRectangle(rectangle: any) {
    const rect = new Konva.Rect({
      x: rectangle.x,
      y: rectangle.y,
      width: rectangle.width,
      height: rectangle.height,
      stroke: 'black',
      strokeWidth: rectangle.strokeWidth,
      dash: [10, 5],
    });
    this.layer.add(rect);
    this.ajouterTitre(this.layerText, rectangle);
    this.layer.draw();
  }

  initialzeImage(rectangle: any, position: boolean) {
    const rect = new Konva.Rect(
      {
        x: rectangle.x,
        y: rectangle.y,
        width: rectangle.width,
        height: rectangle.height,
        stroke: 'black',
        strokeWidth: rectangle.strokeWidth,
        dash: [10, 5],
      }
    );

    const imageObj = new Image();
    imageObj.onload = () => {
      if (position == true) {
        const image = new Konva.Image({
          image: imageObj,
          x: rectangle.x + (rectangle.width * 0.35), // Position x correspondant au rectangle
          y: rectangle.y + (rectangle.height * 0.2), // Position y correspondant au rectangle
          width: imageObj.width / 1.5,
          height: imageObj.height / 1.5,
        });
        this.group = new Konva.Group();
        this.group.add(rect);
        this.group.add(image);
        this.layer.add(this.group);
        this.group.on('click', () => {
          this.showModal(rect);
        });
        this.layer.batchDraw();
      } else {
        const image = new Konva.Image({
          image: imageObj,
          x: rectangle.x,// Position x correspondant au rectangle
          y: rectangle.y, // Position y correspondant au rectangle
          width: rectangle.width,
          height: rectangle.height,
        });
        this.group = new Konva.Group();
        this.group.add(rect);
        this.group.add(image);
        this.layer.add(this.group);
        this.group.on('click', () => {
          this.showModal(rect);
        });
        this.layer.batchDraw();
      }

    }

    this.layer.draw();
    imageObj.src = rectangle.fileBase64;
  }

  initialzeImage2(rectangle: any, position: boolean) {
    const rect = new Konva.Rect({
      x: rectangle.x,
      y: rectangle.y,
      width: rectangle.width,
      height: rectangle.height,
      stroke: 'black',
      strokeWidth: rectangle.strokeWidth,
      dash: [10, 5],
    });
    const imageObj = new Image();
    if (position == true) {
      imageObj.onload = () => {
        const image = new Konva.Image({
          image: imageObj,
          x: rectangle.x + (rectangle.width * 0.3), // Position x correspondant au rectangle
          y: rectangle.y + (rectangle.height * 0.28), // Position y correspondant au rectangle
          width: imageObj.width / 1.5,
          height: imageObj.height / 1.5,
        });
        this.groupCachet = new Konva.Group();
        this.groupCachet.add(rect);
        this.groupCachet.add(image);
        this.layer.add(this.groupCachet);
        this.groupCachet.on('click', () => {
          this.showModalCachet(rect);
        });
        this.layer.batchDraw();
      }
    } else {
      imageObj.onload = () => {
        const image = new Konva.Image({
          image: imageObj,
          x: rectangle.x, // Position x correspondant au rectangle
          y: rectangle.y, // Position y correspondant au rectangle
          width: rectangle.width,
          height: rectangle.height,
        });
        this.groupCachet = new Konva.Group();
        this.groupCachet.add(rect);
        this.groupCachet.add(image);
        this.layer.add(this.groupCachet);
        this.groupCachet.on('click', () => {
          this.showModalCachet(rect);
        });
        this.layer.batchDraw();
      }
    }

    this.layer.draw();
    imageObj.src = rectangle.fileBase64;
  }

  checkValidInput() {
    var allchecked = false;
    this.signatures.forEach((element: SignaturePage) => {
      element.objetSignatureDtos.forEach((data: ObjetSignature) => {
        if (data.typeObjet == "CACHET" || data.typeObjet == "SIGNATURE") {
          if (data.fileBase64 == "") {
            allchecked = true;
          }
        }
      })
    })
    if (allchecked) {
      this.createMessage("warning", "Veuillez signer dans toutes les pages du document");
    } else {
      this.signDocument()
      console.log(this.signatures);
    }
  }


  ajouterTitre(layer: any, rect: any) {

    console.log(rect)
    const text = new Konva.Text({
      x: rect.x, // Position x correspondant au rectangle
      y: rect.y + rect.height * 0.41, // Position y correspondant au rectangle
      text: rect.title,
      fontSize: 13,
      align: 'center',
      fill: 'black',
      width: rect.width
    });
    text.setAttr('rectId', rect.id);
    layer.add(text);
    layer.draw();
  }

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

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

  supprimerTousRectangles(layer: any) {
    const rectangles = this.getAllElements(layer);
    console.log(rectangles);
    rectangles.forEach((rectangle: any) => {
      rectangle.remove();
    });
    layer.batchDraw();
    layer.draw();
    console.log(layer.getChildren())
  }

  getAllElements(layer: any): any[] {
    let elements: any[] = [];
    layer.getChildren().forEach((element: any) => {
      if (element.isGroup) {
        elements = elements.concat(this.getAllElements(element));
      } else {
        elements.push(element);
      }
    });
    return elements;
  }

  supprimerTousText(layer: any) {
    const rectangles = this.getAllElements(layer);
    rectangles.forEach((text: any) => {
      text.remove();
    });
    layer.batchDraw();
    layer.draw();
    console.log(layer.getChildren())
  }

  modifierImage(imagenew: any, group: any, type: string, rect: any) {
    group.getChildren((node: any) => {
      if (node instanceof Konva.Image) {
        const image = new Image();
        image.onload = () => {
          node.image(image);
          node.x(rect.x())
          node.y(rect.y())
          node.width(rect.width());
          node.height(rect.height());
          node.getLayer()!.batchDraw();
        };
        image.src = imagenew;
      } else if (node instanceof Konva.Rect) {
        // Modifier le stroke du rectangle (par exemple)
        node.strokeWidth(0);
        node.getLayer()!.batchDraw();
      }
    });

    this.obejcts.map((elment: any) => {
      if (elment.name == type) {
        elment.fileBase64 = imagenew;
      }
    });

    group.getLayer().batchDraw();
  }

}

