import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from "@angular/router";
import { DomSanitizer } from "@angular/platform-browser";
import { ImageUploaderCrudService } from "@common/crud/crud.service";


export class BaseContractsComponent {
    protected resource: string = "contract";
    protected schema: string = "Contract";
}

@Component({
    templateUrl: '../base-view/templates/list.template.html'
})
export class ContractsListComponent extends BaseContractsComponent {
    columns = ['status', 'name', 'title', 'parties.items.entity.label', 'lawyer.label', 'date'];
    filters = ['status'];
}

@Component({
  templateUrl: '../base-view/templates/new.template.html'
})
export class ContractsNewComponent extends BaseContractsComponent {
    @Input() value: {} = {};
}

@Component({
    template:`
    <ng-container *ngIf="this.resourceReadyToPrint; else previewLink">
        <label i18n>Download Link:</label>
        <div class="input-group mb-12">
          <span class="input-group-text"><a href="{{ this.contractPrintLink! }}" target="_blank">{{ this.contractPrintLink! }}</a></span>
          <button type="button" class="btn btn-light" [cdkCopyToClipboard]="this.contractPrintLink!"><i-bs name="text-paragraph"/></button>
        </div>
    </ng-container>
    <ng-template #previewLink>
        <label i18n>Preview Link:</label>
        <div class="input-group mb-12">
          <span class="input-group-text"><a href="{{ this.contractPreviewLink! }}" target="_blank">{{ this.contractPreviewLink! }}</a></span>
          <button type="button" class="btn btn-light" [cdkCopyToClipboard]="this.contractPreviewLink!"><i-bs name="text-paragraph"/></button>
        </div>    
    </ng-template>
    <base-card
        [resource_id]="this.resource_id"
        [resource]="this.resource"
        [schema]="this.schema"
        (resourceReceived)="this.onResourceReceived($event)">
    </base-card>
    `,
})
export class ContractsCardComponent extends BaseContractsComponent{
    resource_id: string | null = null;
    resourceReadyToPrint = false;
    contractPrintLink: string | null = null;
    contractPreviewLink: string | null = null;

    constructor(
        private route: ActivatedRoute
    ) {
        super()
    }

    ngOnInit(): void {
        if (this.resource_id === null) {
            this.route.paramMap.subscribe((params: ParamMap) => {
                this.resource_id = params.get('id')

            })
        }
    }

    onResourceReceived(model: any): void {
        this.resourceReadyToPrint = model.status != "published";
        this.contractPrintLink = `${location.origin}/api/v1/contract/print/pdf/${this.resource_id}`
        this.contractPreviewLink = `${location.origin}/api/v1/contract/print/preview/${this.resource_id}`
    }
}

@Component({
    template: `
        <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-1">
            <ngb-panel>
                <ng-template ngbPanelTitle>
                    <span i18n>Preview</span>
                </ng-template>
                <ng-template ngbPanelContent>
                    <iframe width="100%" 
                            [src]="getPreview()" 
                            onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";o.style.width=o.contentWindow.document.body.scrollWidth+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
                </ng-template>
            </ngb-panel>
            <ngb-panel>
                <ng-template ngbPanelTitle>
                    <span i18n>Signature</span>
                </ng-template>
                <ng-template ngbPanelContent>
                    <ng-container *ngIf="this.affixed"><ng-container i18n>This Contract has already been signed by</ng-container> {{ this.signatory }}</ng-container>
                    <div class="row" *ngIf="!this.affixed">
                        <signature-drawer class="col-7"
                         (signatureDrawn$)="postSignature($event)"></signature-drawer>
                        <div class="col-5" i18n>
                            <p>Cette page est à la destination exclusive de <strong>{{ this.signatory }}</strong></p>
                            <p>Si vous n'êtes <strong>pas</strong> {{ this.signatory }}, veuillez <strong>fermer cette page immédiatement</strong> et surpprimer tous les liens en votre possession menant vers celle-ci.</p>
                            <p>En vous maintenant et/ou en interagissant avec cette page, vous enfreignez l'article L.229 du code pénal de l'Etat de San Andreas pour <strong>usurpation d'identité</strong> et vous vous exposez ainsi à une amende de 20 000$ ainsi qu'à des poursuites civiles.</p>
                            <p>Le cabinet Cooper, Hillman & Toshi LLC</p>
                        </div>
                    </div>
                </ng-template>
            </ngb-panel>
        </ngb-accordion>
    `
})
export class ContractsSignatureComponent implements OnInit {
    signature_id: string | null = null;
    signature: any = {}
    signatory = ""

    affixed = false;

    constructor(
        private route: ActivatedRoute,
        private sanitizer: DomSanitizer,
        private crudService: ImageUploaderCrudService,
    ) {}

    ngOnInit() {
        this.route.paramMap.subscribe((params: ParamMap) => {
            this.signature_id = params.get('id');
            this.crudService.get('contract/signature', this.signature_id!).subscribe( (response:any) => {
                this.signature = response;
                this.affixed = this.signature.signature_affixed;
                if (this.signature.representative) {
                    this.signatory = this.signature.representative.entity_data.firstname  + " " +  this.signature.representative.entity_data.lastname;
                } else {
                    this.signatory = this.signature.entity.entity_data.firstname  + " " +  this.signature.entity.entity_data.lastname;
                }
            })
        })
    }

    getPreview() {
        return this.sanitizer.bypassSecurityTrustResourceUrl("/api/v1/contract/print/preview/signature/" + this.signature_id);
    }

    postSignature(image: string) {
        this.crudService.upload('contract/signature', this.signature_id!, image).subscribe((v: any) => {
            if (v) {
                this.affixed = true;
            }
        })
    }
}
