import { Host, h } from "@stencil/core";
/**
 * Display a dialog that allows the user to specify an initials image, either by using a signature-font-generated image
 * based on their full name, or by hand-drawing their initials with a mouse or tablet.
 */
export class VerdocsInitialDialog {
    constructor() {
        /**
         * Initial signature text
         */
        this.initials = '';
        this.fontLoaded = false;
        this.enteredInitials = '';
        this.mode = 'type';
    }
    componentWillLoad() {
        this.enteredInitials = this.initials.toUpperCase();
        const ds = new FontFace('Dancing Script', 'url(https://fonts.gstatic.com/s/dancingscript/v19/If2cXTr6YS-zF4S-kcSWSVi_sxjsohD9F50Ruu7BMSo3Sup6hNX6plRP.woff)');
        ds.load().then(font => {
            document.fonts.add(font);
            this.fontLoaded = true;
        });
    }
    componentDidLoad() {
        this.redrawSignature();
    }
    componentDidUpdate() {
        this.redrawSignature();
    }
    redrawSignature() {
        console.log('redrawing sig');
        if (!this.canvasElement) {
            console.log('no canvas');
            return;
        }
        const canvasWidth = this.canvasElement.width;
        console.log('cw', canvasWidth);
        const context = this.canvasElement.getContext('2d');
        context.clearRect(0, 0, this.canvasElement.width, this.canvasElement.height);
        let fontSize = 100;
        do {
            fontSize -= 2;
            context.font = `${fontSize}px Dancing Script`;
        } while (context.measureText(this.enteredInitials).width > canvasWidth - 32); // 32px padding each side
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.font = `${fontSize}px Dancing Script`;
        context.fillText(this.enteredInitials, this.canvasElement.width / 2, this.canvasElement.height / 2);
    }
    handleNameChange(e) {
        this.enteredInitials = e.target.value;
    }
    handleCancel(e) {
        e.stopPropagation();
        e.preventDefault();
        this.exit.emit();
    }
    handleAdopt(e) {
        e.stopPropagation();
        e.preventDefault();
        const data = this.canvasElement.toDataURL('image/png');
        this.next.emit(data);
    }
    /*
    selColor(hex: string) {
      this.color = hex;
      this.animateDraw();
    }
  
    stopDraw() {
      this.paint = false;
      this.adoptedAndSigned = !this.hasSignature();
    }
  
    draw(e) {
      this.paint = true;
      this.addPoints(e, false);
      this.animateDraw();
    }
  
    recordPoints(e) {
      if (this.paint) {
        this.addPoints(e, true);
        this.animateDraw();
      }
    }
  
    animateDraw() {
      this.canvas.clearRect(0, 0, this.canvas.canvas.offsetWidth, this.canvas.canvas.offsetHeight);
  
      this.canvas.strokeStyle = this.color || '#000000';
      this.canvas.lineJoin = 'round';
      this.canvas.lineWidth = 3;
  
      for (let i = 0; i < this.points.length; i++) {
        this.canvas.beginPath();
        if (this.points[i].drag && i) {
          this.canvas.moveTo(this.points[i - 1].x, this.points[i - 1].y);
          // this.canvas.arc(this.points[i - 1].x, this.points[i - 1].y, 2, 0, 2 * Math.PI, false);
        } else {
          this.canvas.moveTo(this.points[i].x - 1, this.points[i].y);
          // this.canvas.arc(this.points[i].x, this.points[i].y, 2, 0, 2 * Math.PI, false);
        }
  
        this.canvas.lineTo(this.points[i].x, this.points[i].y);
        this.canvas.closePath();
        this.canvas.stroke();
      }
    }
  
    drawCurve(color: string, curve: number) {
      this.canvas.beginPath();
    }
  
  
  
    addPoints(e, drag: boolean) {
      if (window) {
        let x;
        let y;
        e.preventDefault();
        if (e.touches && e.touches.length > 0) {
          x = e.touches[0].clientX;
        } else {
          x = e.clientX;
        }
  
        if (e.touches && e.touches.length > 0) {
          y = e.touches[0].clientY;
        } else {
          y = e.clientY;
        }
        const rect = this.signatureCanvas.nativeElement.getBoundingClientRect();
        this.points.push({
          x: x - rect.left,
          y: y - rect.top,
          drag: drag
        });
      }
    }
  
    clearPad() {
      this.canvas.clearRect(0, 0, this.canvas.canvas.offsetWidth, this.canvas.canvas.offsetHeight);
      this.points = [];
      this.adoptedAndSigned = !this.hasSignature();
    }
  
      async adoptAndSign() {
      try {
        this.adoptedAndSigned = true;
        await this.updateFullName();
        await this.captureSignatureFromCanvas();
        const message = this.signatureMode === 'Signature' ? 'Saving Signature' : 'Saving Initial';
        this.snackbarService.open(message, 'OK', this.snackbarService.initConfig(null, 'bottom'));
        this.handleMode();
      } catch (err) {
        this.snackbarService.open('Failed to apply signature', 'OK', this.snackbarService.initConfig(null, 'bottom'));
      }
    }
  
    handleMode() {
      let currentField;
      switch (this.mode) {
        case 'signerview':
          if (this.signatureMode === 'Signature') {
            this.signatureService.postSignatureBlob().then(result => {
              if (result && result.id && result.url) {
                currentField = this.signatureService.currField;
                this.signatureService.updateSigned(currentField.fName, true);
                this.signatureService.toggleSig(false);
                this.signatureService.setSignatureId(result.id);
                this.signatureService.putSignatureField(this.envelopeId, this.fieldName, result.id).then(res => {
                  this.eventTracker.createEvent({
                    category: 'verdoc',
                    action: 'verdoc signed',
                    label: `verdoc id: ${this.envelopeId}`
                  })
                  if (res && res.settings) {
                    this.signatureService.setSignatureData(res.settings.base64);
                    this.signatureService.setSignatureId(res.settings.signature_id);
                  }
                  this.snackbarService.dismiss();
                  this.dialog.close({ status: 'saved', temp_sig: res.settings.base64, sig_id: res.settings.signature_id });
                }).catch(err => {
                  this.snackbarService.open('Failed to save signature. Please try again.', 'DISMISS', {
                    duration: 3000
                  });
                  this.adoptedAndSigned = false;
                  return err;
                });
              }
            });
          } else {
            this.signatureService.postInitialBlob().then(result => {
              if (result && result.id && result.url) {
                currentField = this.signatureService.currField;
                this.signatureService.updateInitialed(currentField.fName, true);
                this.signatureService.setInitialId(result.id);
                this.signatureService.toggleSig(false);
                this.signatureService.putInitialField(this.envelopeId, this.fieldName, result.id).then(res => {
                  if (res && res.settings) {
                    this.signatureService.setInitialData(res.settings.base64);
                    this.signatureService.setInitialId(res.settings.initial_id);
                  }
                  this.snackbarService.dismiss();
                  this.dialog.close({ status: 'saved', temp_int: res.settings.base64, int_id: res.settings.initial_id });
                }).catch(err => {
                  this.snackbarService.open('Failed to save initial. Please try again.', 'DISMISS', {
                    duration: 3000
                  });
                  this.adoptedAndSigned = false;
                  return err;
                });
              }
            });
          }
          break;
      }
    }
     */
    render() {
        return (h(Host, { key: '4085e9b406a11216f58f457e7a0cdfb558792a98', onClick: e => this.handleCancel(e) }, h("div", { key: '4c6a003c8f792fad3ae9b99f94a587501bc2749b', class: "dialog" }, h("div", { key: '4180f88e05069d2218b6f42883e1f907095c7579', class: "heading" }, "Create Your Initial"), h("div", { key: 'fa4fc8d6137c30a22727a915322125042f5786f6', class: "content" }, h("verdocs-text-input", { key: 'afbc49e66e366601720774c105974cb0de3c481e', placeholder: "Initials...", label: "Initials", value: this.enteredInitials, onInput: e => this.handleNameChange(e) }), h("div", { key: '5b21e779b447afd130b819f9aa912378ffea930d', class: "as-shown" }, "As shown on driver's license or govt. ID card."), this.fontLoaded ? h("canvas", { ref: el => (this.canvasElement = el) }) : h("div", { style: { display: 'none' } }), h("div", { key: '75ba8cbf3198ff549cf59410ce359e77eca021af', class: "disclaimer" }, "By clicking Adopt, I agree that the signature will be the electronic representation of my signature for all purposes when I (or my agent) use them on documents, including legally binding contracts \u2014 just the same as a pen-and-paper signature or initial."), h("div", { key: '327877bb6d9cd5cfd268d362ac5cad0cb17c2ce2', class: "buttons" }, h("verdocs-button", { key: 'a0a04659ea55b9ffe7d5f19af3f81119f53e58df', label: "CANCEL", variant: "outline", onClick: e => this.handleCancel(e) }), h("verdocs-button", { key: 'c5bb10699adb3df54a0a07dada14260ce2eab2db', label: "Adopt & Sign", onClick: e => this.handleAdopt(e) }))))));
    }
    static get is() { return "verdocs-initial-dialog"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-initial-dialog.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-initial-dialog.css"]
        };
    }
    static get properties() {
        return {
            "initials": {
                "type": "string",
                "attribute": "initials",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Initial signature text"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "fontLoaded": {},
            "enteredInitials": {},
            "mode": {}
        };
    }
    static get events() {
        return [{
                "method": "next",
                "name": "next",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the initials are adopted."
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }, {
                "method": "exit",
                "name": "exit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the step is cancelled. This is called exit to avoid conflicts with the JS-reserved \"cancel\" event name."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
}
//# sourceMappingURL=verdocs-initial-dialog.js.map
