import styles from './styles.module.css'
import {useEffect, useState} from "react";

export interface ProcessExceptionInterface {
    message: string,
    file: string,
    line: bigint,
    code: bigint,
    trace: any[],
}

export interface ProcessProgressInterface {
    total: bigint,
    progress: bigint,
    memory: any[],
}

export interface ProcessInterface {
    id: string,
    lock: string|null,
    containerUuid: string|null,
    pid: bigint|null,
    name: string,
    options: Record<string, any>,
    arguments: Record<string, any>,
    exception: ProcessExceptionInterface|null,
    progress: ProcessProgressInterface|null,
    createdAt: string,
    updatedAt: string|null,
    startedAt: string|null,
    pausedAt: string|null,
    cancelledAt: string|null
    completedAt: string|null
}

export default function Processes() {
    const [processes, setProcesses] = useState<ProcessInterface[]>([]);

    let refreshProcesses = async () => {
        let response = await fetch('http://fmw.sipachev.sv/system-monitoring/processes', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                'X-Plugin-Token': 'passw0rd'
            },
        });
        const processes: ProcessInterface[] = await response.json()
        setProcesses(processes)
        setTimeout(() => refreshProcesses, 1000)
    }

    useEffect(() => {
        refreshProcesses()
    }, [])


    return (
        <div className={styles.processes}>
            {processes.map((process: ProcessInterface, index: number) => (
                <div className={styles.process} key={index}>
                    <div>
                        {process.name}&nbsp;
                    </div>
                    <div>
                        {!process.progress && 'N/A'}
                        {process.progress && <span>
                            {`${process.progress.progress}`} / {`${process.progress.total}`} - 50% [53Mb] / 20 sec
                        </span>}
                    </div>
                    <div>
                        {process.completedAt && <button>Repeat</button>}
                        {process.pausedAt && <button>Play</button>}
                        {!process.pausedAt && !process.completedAt && !process.cancelledAt && <button>Pause</button>}
                        {!process.completedAt && !process.cancelledAt && <button>Stop</button>}
                    </div>
                </div>
            ))}
        </div>
    )
}
