import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
import Dataset from './dataset.js';
import { builder, create } from 'xmlbuilder2';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import db from '@adonisjs/lucid/services/db';
import { DateTime } from 'luxon';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";

export default class DocumentXmlCache extends BaseModel {
    public static namingStrategy = new SnakeCaseNamingStrategy();
    public static table = 'document_xml_cache';
    // public static fillable: string[] = ['value', 'label', 'type', 'relation'];
    // public static primaryKey = false;
    static primaryKey = ''; // Set primaryKey to null to indicate there is no primary key

    @column({
        isPrimary: true,
    })
    public document_id: number;

    @column({})
    public xml_version: number;

    @column()
    public server_date_modified?: string;

    // @column.dateTime({
    //     autoCreate: true,
    //     autoUpdate: true,
    // })
    // public updated_at?: DateTime;

    @column({})
    public xml_data: string;

    @belongsTo(() => Dataset, {
        foreignKey: 'document_id',
    })
    public dataset: BelongsTo<typeof Dataset>;

    /**
     * Get dom document of 'xml_data' string
     *
     * @returns {XMLBuilder}
     */
    public getDomDocument(): XMLBuilder {
        // const dom = xmlbuilder.create({ version: "1.0", encoding: "UTF-8", standalone: true });
        let dom: XMLBuilder = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, this.xml_data);
        // return dom.first();

        const rdrDataset = dom.find(
            (n) => {
                const test = n.node.nodeName == 'Rdr_Dataset';
                return test;
            },
            false,
            true,
        )?.node;

        if (rdrDataset == undefined) {
            return dom.first();
        } else {
            dom = builder({ version: '1.0', encoding: 'UTF-8', standalone: true }, rdrDataset);
            return dom;
        }
    }

    /**
     * Check if a dataset in a specific xml version is already cached or not.
     *
     * @param mixed datasetId
     * @param mixed serverDateModified
     * @returns {Promise<boolean>} Returns true on cached hit else false.
     */
    // public static async hasValidEntry(datasetId: number, datasetServerDateModified: DateTime): Promise<boolean> {
    //     // const formattedDate = dayjs(datasetServerDateModified).format('YYYY-MM-DD HH:mm:ss');

    //     const query = Database.from(this.table)
    //         .where('document_id', datasetId)
    //         .where('server_date_modified', '2023-08-17 16:51:03')
    //         .first();

    //     const row = await query;
    //     return !!row;
    // }

    // Assuming 'DocumentXmlCache' has a table with a 'server_date_modified' column in your database
    public static async hasValidEntry(datasetId: number, datasetServerDateModified: DateTime): Promise<boolean> {
        const serverDateModifiedString: string = datasetServerDateModified.toFormat('yyyy-MM-dd HH:mm:ss'); // Convert DateTime to ISO string
        const query = db.from(this.table)
            .where('document_id', datasetId)
            .where('server_date_modified', '>=', serverDateModifiedString) // Check if server_date_modified is newer or equal
            .first();

        const row = await query;
        return !!row;
    }
}
