import { useEffect, useState } from 'react'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import LoaderPortal from '../../components/LoaderPortal'
import { EditableTable, makeActionHandler, makeColumn } from '../../components/Table'
import { AdminPermissionInfoService } from '../../services/api'
import PermissionBits, { toHexString } from './PermissionBits'

export const PermissionController = () => {
    const [permissions, setPermissions] = useState([])
    const [showLoader, setShowLoader] = useState(false)

    const columns = [
        makeColumn('Название', 'name', { width: 200, editable: true }),
        makeColumn('Описание', 'description', { width: 200, editable: true }),
        makeColumn('Значения битов', 'bitDescription', {
            width: 200,
            editable: true,
            input: <PermissionBits />, // TODO: Дописать колонку для описания битов права
            render: (bits) => {
                if (!bits) return '--'
                const sum = Object.keys(bits).reduce((sum, key) => sum + (1 << parseInt(key)), 0)
                return sum && toHexString(sum, 16)
            },
        })
    ]

    const updateTable = () => invokeWebApiWrapperAsync(
        async () => {
            const permissions = await AdminPermissionInfoService.getAll()
            setPermissions(permissions)
        },
        setShowLoader,
        `Не удалось загрузить список прав`
    )

    useEffect(updateTable, [])

    const handlerProps = {
        service: AdminPermissionInfoService,
        setLoader: setShowLoader,
        errorMsg: `Не удалось выполнить операцию`,
        onComplete: updateTable
    }

    return (
        <LoaderPortal show={showLoader}>
            <EditableTable
                size={'small'}
                bordered
                columns={columns}
                dataSource={permissions}
                onRowAdd={makeActionHandler('insert', handlerProps)}
                onRowEdit={makeActionHandler('update', handlerProps)}
                onRowDelete={makeActionHandler('delete', handlerProps)}
            />
        </LoaderPortal>
    )
}

export default PermissionController
