import React, { Component } from "react";
import * as ReactDom from "react-dom/client";
import DataTable from 'datatables.net-react';
import {HostnameServiceDescription, Service} from "../../src/models/service";
import menu from "./menu";

interface SingleServiceProp {
    hostname: string;
    serviceName: string;
    status: string;
}

interface SystemServiceState {
    loading: boolean;
}

interface SystemServiceProps {
    data: SingleServiceProp[];
}

export class SystemServiceComponent extends Component<SystemServiceProps, SystemServiceState> {
    public constructor(props: SystemServiceProps) {
        super(props);

        this.state = {
            loading: false,
        };
        menu.addFilterEventListener(() => {
            this.refreshFilter();
        });
    }

    private refreshFilter() {
        // FIXME
        /*
        const hidden = this.isFiltered();
        if (hidden === this.state.hidden)
            return;
        this.setState({...this.state, hidden: hidden});
        */
    }

    public render(): React.JSX.Element {
        if (this.state.loading)
            return (<>Loading..</>);
        else if (this.props.data === null)
            return (<>Error</>);
        return (<>
            <DataTable options={{
                    layout: { topEnd: null },
                    columnDefs: [
                        { target: 0, columnControl: { target: 0, content: [ "order", [ "searchList" ] ] } },
                        { target: 1, columnControl: { target: 0, content: [ "order", [ "search" ] ] } },
                        { target: 2, columnControl: { target: 0, content: [ "order", [ "searchList" ] ] } }
                    ],
                    pageLength: 20,
                    lengthMenu: [10, 20, 50, 100, -1],
                    ordering: {
                        indicators: false,
                        handler: false
                    }
                }} data={this.props.data.map(x => [ x.hostname, x.serviceName, x.status ])}>
                <thead><tr>
                    <th>Host</th>
                    <th>Service Name</th>
                    <th>Status</th>
                </tr></thead>
            </DataTable>
            </>);
    }

    public static renderMultiple(container: HTMLElement, data: HostnameServiceDescription): void {
        const dataArray: SingleServiceProp[] = Object.keys(data).reduce((acc: SingleServiceProp[], hostname: string): SingleServiceProp[] => {
            return acc.concat(data[hostname]!.map((x: Service) : SingleServiceProp => { return { hostname: hostname, serviceName: x.name, status: x.statusText }}));
        }, []);
        ReactDom.createRoot(container).render(<SystemServiceComponent data={dataArray}/>);
    }
}

