import React, { useState, useEffect, useMemo, useCallback,Component } from 'react';
import {batch, shallowEqual,connect, useSelector, useDispatch} from 'react-redux'
import * as Common from './common'
import * as Shared from 'placeholder-shared'
import * as Antd from 'antd'
import * as Task from './Task'
import * as Immer from 'immer';

const getKey = (database,dataset, table) => {
    if (!database||!dataset || !table)
        return ''
    return `${database}-${dataset}-${table}`
}

export const SourceTables = (props: { stepCounter:number, onSelect: (keys: any[], e: any) => any }) => {
    const { onSelect,stepCounter} = props
    const [tables, setTables] = useState(null)
    const operation = useSelector(state => (state as any).steps[stepCounter].operation)
    const userConfig:Shared.State.IUserConfig = useSelector(state=> (state as any).userConfig)

	useEffect(() => {
        /*
		console.log("running get sources")
		Shared.Runner.runQuery({}, 'listTables', {}).then((tables) => {
            console.log("got tables", tables)
            setTables(tables)
        })
        */
       Shared.Snowflake.runListTables(userConfig).then((tables:
           Shared.Runner.TableList) => {
           setTables(tables)
       }).catch((err) => {
           Antd.message.error(<span>Unable to get tables! {Shared.Common.getValueSafe(err, ['error', 'message'], null)}</span>
           )
       }
       )
    }, [userConfig])
    const treeData = useMemo(() => {
        return !tables ? null : Object.keys(tables).map((database) => {
            return {
                title: database, key: database, isLeaf: false,
                children:
                    Object.keys(tables[database]).map((schema) => {
                        return {
                            title: schema,
                            key: `${database}-${schema}`,
                            isLeaf: false,
                            children: tables[database][schema].map((table) => {
                                return {
                                    title: table,
                                    key: getKey(database, schema, table),
                                    isLeaf: true
                                }
                            })
                        }
                    })
            }
        })
    }, [tables]
    )
    const selectedKeys = [getKey(operation.database,operation.dataset, operation.table)]
    console.log("recomputing selectedkeys", selectedKeys)
    const tree = tables ? <Antd.Tree.DirectoryTree
        multiple={false}
        defaultExpandAll={false}
        selectedKeys={selectedKeys}
        onSelect={onSelect}
        //onExpand={onExpand}
        treeData={treeData}
    /> : null;
    return tree;
}