import useSWR from 'swr'
import { fetcher } from '../../http/axiosInstance'
import { BASE_URL } from '../../constants'
import { IObjectParam, IParam } from '../../interfaces/objects'
import TCBParameter from './TCBParameter'
import TableValue from './TableValue'

interface ObjectParameterProps {
    showLabel?: boolean,
    param: IObjectParam,
}

const ObjectParameter = ({
    param
}: ObjectParameterProps) => {
    const { data: paramData } = useSWR(
        `/general/params/all?param_id=${param.id_param}`,
        (url) => fetcher(url, BASE_URL.ems).then(res => res[0] as IParam),
        {
            revalidateOnFocus: false,
            revalidateIfStale: false
        }
    )

    const Parameter = (type: string, name: string, value: unknown, vtable: string, unit: string | null) => {
        switch (type) {
            case 'bit':
                return (
                    <TableValue value={value} name={name} type='boolean' />
                )
            case 'bigint':
                return (
                    <TableValue value={value} name={name} type='number' />
                )
            case 'tinyint':
                return (
                    <TableValue value={value} name={name} type='number' />
                )
            // TODO: Calculate from calc procedures
            case 'calculate':
                return (
                    <TableValue value={value} name={name} type='value' />
                )
            case 'GTCB':
                return (
                    <TCBParameter value={value as string} vtable={vtable} name={name} />
                )
            case 'TCB':
                return (
                    <TCBParameter value={value as string} vtable={vtable} name={name} />
                )
            case type.match(/varchar\((\d+)\)/)?.input:
                return (
                    <TableValue value={value} name={name} type='string' />
                )
            case type.match(/numeric\((\d+),(\d+)\)/)?.input:
                return (
                    <TableValue value={value} name={name} type='number' unit={unit} />
                )
            case 'year':
                return (
                    <TableValue value={value} name={name} type='number' />
                )
            case 'uniqueidentifier':
                return (
                    <TableValue value={value} name={name} type='value'/>
                )
            default:
                return (
                    <div>
                        {name}
                        {value as string}
                    </div>
                )
        }
    }

    return (
        <>
            {paramData &&
                Parameter(paramData.format, paramData.name, param.value, paramData.vtable, paramData.unit)
            }
        </>
    )
}

export default ObjectParameter