import {Component, EventEmitter, Input, OnInit, Output} from "@angular/core";
import {JSONSchema7} from "json-schema";
import {JsonschemasService} from "@common/crud/jsonschemas.service"
import {FormGroup} from "@angular/forms";
import {FormlyFieldConfig} from "@ngx-formly/core";
import {CrudFormlyJsonschemaService} from "@common/crud/crud-formly-jsonschema.service";

@Component({
    selector: 'crud-list-filter-list',
    template: `
        <formly-form [form]="form" [fields]="fields" [model]="this.searchTerms" (modelChange)="onModelChange($event)"></formly-form>
    `,
})
export class FilterListComponent implements OnInit {
    @Input() filters: string[] = [];
    @Input() schema = "";
    @Input() values = {};

    @Output() filterChange: EventEmitter<{[key: string]: any}> = new EventEmitter();

    form = new FormGroup({});
    fields: FormlyFieldConfig[] = [];

    searchTerms: {[key: string]: string | {}} = {}

    public fieldJson = {
        components: {},
        type: "object",
        properties: {},
    }

    constructor(private jsonSchemasService: JsonschemasService,
                private formlyJsonschema: CrudFormlyJsonschemaService,) { }

    ngOnInit() {
        this.jsonSchemasService.getUpdateResource(this.schema!).subscribe({
            next: (schema: any) => this.getFilterDefinition(schema),
            error: (err) => console.log(err) /*this.error.emit("Error loading the schema:" + err)*/
        });
    }

    getFilterDefinition(schema: JSONSchema7) {
        const properties: {[key: string]: JSONSchema7} = {}
        for (let filter of this.filters) {
            if (this.jsonSchemasService.path_exists(schema, filter)) {
                let prop = this.jsonSchemasService.get_property_by_path(schema, filter)
                if (prop.hasOwnProperty('allOf')) {
                    // @ts-ignore
                    prop = schema.components.schemas[prop.allOf![0]['$ref'].replace('#/components/schemas/', '')];
                    prop.type = "array";
                    prop.items = {"type": "string", "enum": prop.enum};

                    if (filter in this.values) {
                        this.searchTerms[filter] = {};
                        // @ts-ignore
                        for (let val of this.values[filter]) {
                            // @ts-ignore
                            this.searchTerms[filter][val] = true;
                        }
                    }
                } else if(true) {
                }

                if (prop.hasOwnProperty('readOnly') && prop.readOnly) {
                    prop.readOnly = false
                }
                properties[filter] = prop;
            }
        }
        // @ts-ignore
        this.fieldJson.components = schema.components;
        this.fieldJson.properties = properties;

        // @ts-ignore
        this.fields = [this.formlyJsonschema.toFieldConfig(this.fieldJson)]
    }

    onModelChange(event: {[key: string]: any}) {
        for (let p_name in event) {
            // @ts-ignore
            let p = this.fieldJson.properties[p_name]
            if (p.type == "array" && !Array.isArray(p.items)) {
                let value = []
                for (let key in event[p_name]) {
                    if (event[p_name][key]) {
                        value.push(key)
                    }
                }

                if (value.length == 0 || value.length == p.items.enum.length) {
                    delete event[p_name];
                } else {
                    event[p_name] = value;
                }
            }
        }
        this.filterChange.next(event);
    }
}
