import { Component, Input, OnInit } from '@angular/core';
import { FormlyFieldConfig } from "@ngx-formly/core";
import { FormGroup} from "@angular/forms";
import { CrudFormlyJsonschemaService } from "@common/crud/crud-formly-jsonschema.service";
import { CrudService } from "@common/crud/crud.service";
import { ActivatedRoute, ParamMap, Router } from "@angular/router";

import { formatDate } from "@angular/common";
import {FlashmessagesService} from "../../layout/flashmessages/flashmessages.service";


export class BaseDraftsComponent {
    protected resource: string = "contract/draft";
    protected schema: string = "ContractDraft";
}

@Component({
    templateUrl: '../base-view/templates/list.template.html'
})
export class DraftsListComponent extends BaseDraftsComponent {
    columns = ['status', 'name', 'title', 'parties.items.part'];
    filters = ['status'];
}

@Component({
    selector: 'draft-new-form',
    template: `<base-new [resource]="this.resource" [schema]="this.schema" [model]="this.value"></base-new>`
})
export class DraftsNewFormComponent extends BaseDraftsComponent {
    @Input() value: {} = {};
}

@Component({
    selector: 'draft-new',
    template: `
        <formly-form [fields]="temaplateFormfields" [form]="temaplateForm"></formly-form>
        <draft-new-form [value]="this.templateModel"></draft-new-form>
    `
})
export class DraftsNewComponent extends BaseDraftsComponent implements OnInit {
    templateModel: {} = {};
    temaplateFormfields: FormlyFieldConfig[] = [];
    temaplateForm: FormGroup = new FormGroup({});

    fieldJson = {
        type: "object",
        properties: {
            template_id: {
                type: "string",
                title: "Find a template",
                foreignKey: {
                    reference: {
                        resource: "template/contract",
                        schema: "ContractTemplate"
                    }
                }
            }
        },
    }

    constructor(private formlyJsonschema: CrudFormlyJsonschemaService,
                private crudService: CrudService
    ) {
        super();
    }

    ngOnInit() {
        // @ts-ignore
        this.temaplateFormfields = [this.formlyJsonschema.toFieldConfig(this.fieldJson)];
        this.temaplateForm.valueChanges.subscribe((values) => {
            if (values.template_id !== undefined) {
                this.crudService.get("template/contract", values.template_id).subscribe((templateModel) => {
                    delete templateModel._id;
                    delete templateModel.created_at;
                    delete templateModel.updated_at;
                    delete templateModel.label;
                    const provisions = [];
                    for (const p of templateModel.provisions) {
                        provisions.push({
                            provision: { type: "template", provision_template_id: p.provision_template_id}
                        })
                    }
                    templateModel.provisions = provisions;
                    this.templateModel = templateModel;
                });
            } else {
                this.templateModel = {};
            }
        })
    }
}

@Component({
    template: `
        <base-card
            [resource]="this.resource"
            [schema]="this.schema"
            (resourceReceived)="this.onResourceReceived($event)"
        >
        </base-card>
        <a class="btn btn-link" href="/api/v1/contract/print/preview/draft/{{this.resource_id}}" target="_blank"  i18n>Preview</a>
        <ng-container *ngIf="this.isReadyForPublication;">
            <formly-form [fields]="newContractFormfields" [form]="newContractForm" [model]="newContractModel"></formly-form>
            <button class="btn btn-success" (click)="publish()" i18n>Publish</button>
        </ng-container>
    `
})
export class DraftsCardComponent extends BaseDraftsComponent implements OnInit {
    resource_id: string | null = null;
    templateModel: {} = {};
    isReadyForPublication = false;
    newContractFormfields: FormlyFieldConfig[] = [];
    newContractForm: FormGroup = new FormGroup({});
    newContractModel: any = {
        date: formatDate(new Date(), 'YYYY-MM-dd', 'EN_US', 'CET'),
        location: "Los Santos, SA",
        draft_id: null
    }

    fieldJson = {
        type: "object",
        required: ["date", "location", "draft_id"],
        properties: {
            date: {
                type: "string",
                format: "date",
                title: "Date"
            },
            location: {
                type: "string",
                title: "Location"
            },
            draft_id: {
                type: "string",
                title: "Contract Draft",
                hidden: true
            },
        },
    }

    constructor(
        private route: ActivatedRoute,
        private formlyJsonschema: CrudFormlyJsonschemaService,
        private crudService: CrudService,
        private router: Router,
        private flashService: FlashmessagesService,
    ) {
        super();
    }

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

        this.newContractModel.draft_id = this.resource_id;
        // @ts-ignore
        this.newContractFormfields = [this.formlyJsonschema.toFieldConfig(this.fieldJson)];
    }

    publish() {
        this.crudService.create('contract', this.newContractModel).subscribe({
            next: (response: any) => this.router.navigate([`../../contracts/${response.id}`], {relativeTo: this.route}),
            error: (err) => this.flashService.error(err)
        });
    }

    onResourceReceived(model: any): void {
        this.isReadyForPublication = model.status == "ready";
    }
}
