import React, {useEffect, useState, useCallback} from 'react';
import { shallowEqual, useDispatch, useSelector , batch} from "react-redux";
//import logo from './logo.svg';
import './App.scss';
import './common.scss';
import 'antd/dist/antd.css'
import * as Drag from './Drag'
import * as Data from './Data'
import * as mainWindow from './mainWindow'
import { Icon, Sticky,  Segment, Menu, Button, Sidebar, Container, Grid } from 'semantic-ui-react'
import { Link } from 'react-router-dom'
import 'esprima'
import 'crypto-js'
import 'react-monaco-editor'
import 'sway'
import * as Shared from 'placeholder-shared'
import * as Common from './common'
import * as LeftHeader from './LeftHeader'
import * as StepMenu from './StepMenu'
import * as Steps from './Steps2'
import * as Antd from 'antd'
import * as Loader from './loader'
import Split from 'react-split'
import * as JobResults from './JobResults' 
import * as Settings from './Settings' 
import * as VersionControl from './VersionControl'
import { createLogger } from 'redux-logger'
import * as HotKeys from 'react-hotkeys-hook'
import * as SQLStepMenu from './SQLStepMenu'
import * as Datasets from './Datasets'

import * as RunResult from './RunResult'

import {
	SubnodeOutlined,
	DeploymentUnitOutlined,
	SettingOutlined	,
	UserOutlined
} from '@ant-design/icons';


//import LogRocket from 'logrocket';
var classNames = require('classnames')

//const {remote} = require('electron')
//const {Menu,MenuItem} as Remote = remote

//if (!window.location.host.startsWith("devel"))
	//LogRocket.init('ds65w0/structurerest');
export const getCopyPasteItems = () => {
	return []
	/*
	return [new remote.MenuItem({
		label: 'Copy',
		accelerator: "CmdOrCtrl+C",
		selector: "copy:",
	}),
	new remote.MenuItem({
		label: 'Paste',
		accelerator: "CmdOrCtrl+V",
		selector: "paste:",

	})
	]
	*/
}

const init = () => {
}

init()
import * as LeftBar from './LeftBar'


window.utils = Shared.Utils

export const App = (props)=> {
	const dispatch = useDispatch()
	let myClassName = classNames('grid', 'MainApp',
	)

	useHotKeys()

	const [barSplitValue, barSplitChangeLayout] = Drag.useChangeLayout(72, 'barSplit')
	const [mainSplitValue, mainSplitChangeLayout] = Drag.useChangeLayout(30,'mainSplit')

	const stepCounter = useSelector(state => (state ).currentStep)
	const stepData = useSelector(state => (state ).steps[stepCounter])

	const mainDragEnd = useCallback((sizes) => {
		mainSplitChangeLayout(sizes[0])
	}, [mainSplitChangeLayout])
	const barSplitEnd= useCallback((sizes) => {
		barSplitChangeLayout(sizes[0])
	}, [barSplitChangeLayout])
	const elementStyleCBRow = (dimension, elementSize, gutterSize, index) => {
		return {
			'flex-basis': `calc(${elementSize}% - ${gutterSize}px)`
		}
	}
	const elementStyleCB = (dimension, elementSize, gutterSize, index) => {
		return {
			'flex-basis': `calc(${elementSize}% - ${gutterSize}px)`
		}
	}
	const mainWindowHide = useSelector(state => Shared.Common.getValueSafe(state, ['UIState', 'mainWindowHide'], false))
	const getMainContent = () => {
		return <Common.DivWithClassName key='dataView' className={
			Common.classNames({
				'flexGrow':true, 
				'columnFlexBox':true
			})}
			>
			<StepMenu.StateStepMenu/>
		</Common.DivWithClassName>
	}

	const isAddSqlActivated = useSelector(state => (state ).UIState.isAddSqlActivated)
	const emptyNameActivated = useSelector(state => (state ).UIState.emptyNameActivated)
	const getMain = useCallback(() => {
		const mainChildren = <Common.DivWithClassName className='columnFlexBox flexGrow'>
			<LeftBar.StateLeftBar className='' />
		</Common.DivWithClassName>
		let rightSide = <Common.DivWithClassName className={
			Common.classNames({
				flexGrow:true,
				columnFlexBox:true,
			})}
			>
			{getMainContent()}
		</Common.DivWithClassName>
		const barSplitToUse = mainWindowHide ? 99 : barSplitValue
		return mainChildren;
		return <Split minSize={50} gutterSize={4} onDragEnd={barSplitEnd} sizes={[barSplitToUse, 100 - barSplitToUse]} className='rowFlexBox flexGrow' direction='horizontal'>
			{mainChildren}
			{rightSide}
		</Split>
	},[barSplitEnd, barSplitValue, mainWindowHide,])
	const disableBackdrop = useCallback(()=> {
		dispatch(Shared.State.changeUIState('isAddSqlActivated',false))
		dispatch(Shared.State.changeUIState('emptyNameActivated',false))
	}, [dispatch])
	const collapsed = useSelector(state => (state ).UIState.siderCollapsed)
	const onCollapse = useCallback((collapsed) => {
		console.log("got collapsed", collapsed)
		dispatch(Shared.State.changeUIState('siderCollapsed',collapsed ))

	}, [dispatch])
	const area = useSelector(state => Shared.Common.getValueSafe(state, ['UIState', 'appArea'], 'editor'))
	const getArea = () => {
		switch (area) {
			case 'editor':
				return <><Common.DivWithClassName className=' columnFlexBox flexGrow width100Percent height100Percent backgroundWhite flexGrow'>
					{getMain()}
				</Common.DivWithClassName>
					<Common.DivWithClassName onClick={disableBackdrop} className={
						Common.classNames({
							backDrop: true,
							isAddSqlActivated,
						})}
					>
						<StepMenu.StepMonitor />
					</Common.DivWithClassName>
					</>
			case 'history':
				return <Common.DivWithClassName className='width100Percent backgroundWhite flexGrow columnFlexBox'><JobResults.JobResults /></Common.DivWithClassName>
			case 'settings':
				return <Common.DivWithClassName className='backgroundWhite height100Percent flexGrow'><Settings.Settings/></Common.DivWithClassName>

		}

	}

	const onAppAreaChange = ({item,key,keyPath,selectedKeys}) => {
		if (key == 'none')
			key = 'editor'
		dispatch(Shared.State.changeUIState('appArea', key))
	}
	useEffect(() => {
		if (Shared.Common.isDemoEnvironment() && Shared.Common.isProd())
        dispatch(Shared.Runner.PlayTaskThunk(1, ()=>{},null))
	},[])
	return (
		<>
		<Loader.StateLoader/>
			<Antd.Layout >
				<Antd.Layout.Header className='rowFlexBox boxshadow1' style={{ padding:'0px', height: '30px' ,lineHeight:'30px'}}>
					<Antd.Menu  onSelect={onAppAreaChange} selectedKeys={[area]} theme='dark' mode="horizontal" className='rowFlexBox AppArea'>
						<Antd.Menu.Item key="none" >
							<Common.DivWithClassName className='rowFlexBox'>
								<span>
									Structure
								</span>
							</Common.DivWithClassName>
						</Antd.Menu.Item>
						<Antd.Menu.Item className='rowFlexBox' key="editor" icon={<SubnodeOutlined />}>
							<Antd.Space>
								Editor
							</Antd.Space>
						</Antd.Menu.Item>
						{Shared.Common.isCommandLine() == false &&
							<Antd.Menu.Item key="history" icon={<DeploymentUnitOutlined />}>
								History
							</Antd.Menu.Item>
						}
						<Antd.Menu.Item key="settings" icon={<SettingOutlined/>}>
						Settings	
							</Antd.Menu.Item>
					</Antd.Menu>
					<Common.DivWithClassName className='floatRight'>
						<Antd.Space style={{ paddingRight: '10px' }}>
							<VersionControl.VersionControlMenu />
							<Antd.Avatar size='small' icon={<UserOutlined />} />
						</Antd.Space>
						<VersionControl.VersionControlModal />
					</Common.DivWithClassName>
				</Antd.Layout.Header>
				<Antd.Layout.Content className='paddingTop5px rowFlexBox flexGrow MainContentContainer ' style={{}}>
					{/*<Datasets.DatasetTree/>*/}
					{getArea()}
				</Antd.Layout.Content>
			</Antd.Layout>
		</>
	)
}

export const StateApp = (props) => {
	return <Loader.StoreContext><App /></Loader.StoreContext>
}
//connect(appMapStateToProps, appMapDispatchToProps)(App);
//export default DragDropContext(HTML5Backend)(withRouter(StateApp))
export const Sheets = (props) => {
}

export const useHotKeys = () => {
	const dispatch = useDispatch()

	const currentStepGraph = useSelector(state => (state).currentStepGraph)
	const onViewDependencies = StepMenu.useViewDependencies(currentStepGraph)
	const onChangeTab = StepMenu.useChangeTab()
	const hotKeyOpt = {
		filter:(event)  => true
	}
	const runPreview = useCallback(() => {
		dispatch((dispatch, getState) => {
			const currentStep = getState().currentStep
			if (currentStep) {
				dispatch(Shared.Runner.runStepPreview(currentStep))

			}
		})

		return false;
	},[dispatch])
	HotKeys.useHotkeys('ctrl+enter,command+enter',
		runPreview
	, hotKeyOpt)
	/*
	HotKeys.useHotkeys('command+d', (e) => {
		batch(() => {
			onViewDependencies()
		})
		e.preventDefault()
		return false;
	}, hotKeyOpt)
	*/
	HotKeys.useHotkeys('ctrl+e,command+e', () => {
		batch(() => {
			dispatch(Shared.State.previousTabAction())
		})
		return false;
	}, hotKeyOpt)
	/*
	HotKeys.useHotkeys('command+g', () => {
		dispatch(Shared.State.changeUIState('mainWindowActiveTab', 'graph'))
		return false;
	}, hotKeyOpt)
	*/

}