// @flow

import React, { useState, useRef, useCallback } from "react"
import { makeStyles } from "@material-ui/core/styles"
import Sidebar from "../Sidebar"
import ImageCanvas from "../ImageCanvas"
import Header from "../Header"
import IconTools from "../IconTools/index"
import styles from "./styles"
import useKey from "use-key-hook"
import classnames from "classnames"
import { useSettings } from "../SettingsProvider"
import SettingsDialog from "../SettingsDialog"
import Fullscreen from "../Fullscreen"
import getActiveImage from "../Annotator/reducers/get-active-image"
import { useDispatchHotkeyHandlers } from "../ShortcutsManager"
import { withHotKeys } from "react-hotkeys"
import * as resultFile from '../libs/createFile';

const useStyles = makeStyles(styles)

export let selectRegion = null;
export let selectTool   = null;
export let getState     = null;
export let setFileAttr  = null;
export let exeAction    = null;

const HotkeyDiv = withHotKeys(({ hotKeys, children, divRef, ...props }) => (
  <div {...{ ...hotKeys, ...props }} ref={divRef}>
    {children}
  </div>
))

export const MainLayout = ({
  state,
  dispatch,
  alwaysShowNextButton = false,
  alwaysShowPrevButton = false,
  RegionEditLabel,
  onRegionClassAdded,
  changeSelectedIndex,
  onStateChange,
  selectedIndex,
  init_idx,
  displayTools,
}) => {
  const classes = useStyles()
  const settings = useSettings()

  const memoizedActionFns = useRef({})
  const action = (type, ...params) => {
    const fnKey = `${type}(${params.join(",")})`
    if (memoizedActionFns.current[fnKey])
      return memoizedActionFns.current[fnKey]

    const fn = (...args) =>
      params.length > 0
        ? dispatch(
            ({
              type,
              ...params.reduce((acc, p, i) => ((acc[p] = args[i]), acc), {}),
            })
          )
        : dispatch({ type, ...args[0] })
    memoizedActionFns.current[fnKey] = fn
    return fn
  }

  const { currentImageIndex, activeImage } = getActiveImage(state)
  let nextImage
  if (currentImageIndex !== null) {
    nextImage = state.images[currentImageIndex + 1]
  }

  useKey(() => dispatch({ type: "CANCEL" }), {
    detectKeys: [27],
  })

  const innerContainerRef = useRef()
  const hotkeyHandlers = useDispatchHotkeyHandlers({ dispatch })

  React.useEffect(() => {
    if(state.images[0]){
    // if(state.images[selectedIndex]){
      const result = resultFile.fn_getJsonFile(state.images[0]);
      // const result = resultFile.fn_getJsonFile(state.images[selectedIndex]);

      if(typeof onStateChange === "function"){
        onStateChange(result, selectRegion);
      }
    }
  }, [state.images]);


  const refocusOnMouseEvent = useCallback((e) => {
    if (!innerContainerRef.current) return
    if (innerContainerRef.current.contains(document.activeElement)) return
    /* 해당 영역 포커싱 */
    if (innerContainerRef.current.contains(e.target)) {
      innerContainerRef.current.focus()
      e.target.focus()
    }
  }, [])

  selectRegion = (p_region) => {
    return dispatch({ type: "SELECT_REGION", region : p_region, source : "region_select_box" })
  }

  selectTool = () => {
    return dispatch({type: "SELECT_TOOL", selectedTool: "select"});
  }

  getState = () => {
    return state;
  }

  setFileAttr = (changedImages, activeImage, regionClsList) => {
    return dispatch({type: "SET_FILE_ATTR", changedImages, activeImage, regionClsList});
  }

  exeAction = (type) => {
    return dispatch({type});
  }

  return (
    <Fullscreen
      enabled={state.fullScreen}
      onChange={(open) => {
        if (!open) {
          action("HEADER_BUTTON_CLICKED", "buttonName")("Exit Fullscreen")
        }
      }}
    >
      <HotkeyDiv
        tabIndex={-1}
        divRef={innerContainerRef}
        onMouseDown={refocusOnMouseEvent}
        onMouseOver={refocusOnMouseEvent}
        allowChanges
        handlers={hotkeyHandlers}
        className={classnames(
          classes.container,
          state.fullScreen && "Fullscreen"
        )}
        // 이거 고민좀
        style={{ height: "100%", minWidth: "1150px" }}
      >
        <div>
          <Header
            onHeaderButtonClick={action("HEADER_BUTTON_CLICKED", "buttonName", "changeSelectedIndex")}
            alwaysShowNextButton={alwaysShowNextButton}
            alwaysShowPrevButton={alwaysShowPrevButton}
            inFullScreen={state.fullScreen}
            multipleImages={state.images && state.images.length > 1}
            title={activeImage ? activeImage.name : "No Image Selected"}
            changeSelectedIndex={changeSelectedIndex}
            
          />
        </div>
        <div className={classes.workspace}>
          <div className={classes.iconToolsContainer}>
            <IconTools
              enabledTools={state.enabledTools}
              showTags={state.showTags}
              showMask={state.showMask}
              selectedTool={state.selectedTool}
              onClickTool={action("SELECT_TOOL", "selectedTool")}
              displayTools={displayTools}
            />
          </div>
            {state.annotationType === "image" && !state.selectedImage ? (
            <div className={classes.imageCanvasContainer} style={{ alignItems: "center" }} >
              <div className={classes.noImageSelected} >No Image Selected</div>
            </div>
            ) : (
            <div className={classes.imageCanvasContainer} >
              <div className={classes.imageCanvas}>
                <ImageCanvas
                  {...settings}
                  showCrosshairs={true}
                  key={state.selectedImage}
                  showMask={state.showMask}
                  fullImageSegmentationMode={state.fullImageSegmentationMode}
                  autoSegmentationOptions={state.autoSegmentationOptions}
                  showTags={state.showTags}
                  allowedArea={state.allowedArea}
                  regionClsList={state.regionClsList}
                  regionTagList={state.regionTagList}
                  regions={activeImage.regions || []}
                  realSize={activeImage ? activeImage.realSize : undefined}
                  imageSrc={state.selectedImage}
                  pointDistancePrecision={state.pointDistancePrecision}
                  createWithPrimary={state.selectedTool.includes("create")}
                  dragWithPrimary={state.selectedTool === "pan"}
                  zoomWithPrimary={state.selectedTool === "zoom"}
                  showPointDistances={state.showPointDistances}
                  onMouseMove={action("MOUSE_MOVE")}
                  onMouseDown={action("MOUSE_DOWN")}
                  onMouseUp={action("MOUSE_UP")}
                  onChangeRegion={action("CHANGE_REGION", "region")}
                  onBeginRegionEdit={action("OPEN_REGION_EDITOR", "region")}
                  onCloseRegionEdit={action("CLOSE_REGION_EDITOR", "region")}
                  onDeleteRegion={action("DELETE_REGION", "region")}
                  onBeginBoxTransform={action(
                    "BEGIN_BOX_TRANSFORM",
                    "box",
                    "directions"
                  )}
                  onBeginMovePolygonPoint={action(
                    "BEGIN_MOVE_POLYGON_POINT",
                    "polygon",
                    "pointIndex"
                  )}
                  onAddPolygonPoint={action(
                    "ADD_POLYGON_POINT",
                    "polygon",
                    "point",
                    "pointIndex"
                  )}
                  onSelectRegion={action("SELECT_REGION", "region")}
                  onBeginMovePoint={action("BEGIN_MOVE_POINT", "point")}
                  onImageLoaded={action("IMAGE_LOADED", "image")}
                  RegionEditLabel={RegionEditLabel}
                  onImageOrVideoLoaded={action(
                    "IMAGE_OR_VIDEO_LOADED",
                    "metadata"
                  )}
                  onRegionClassAdded={onRegionClassAdded}
                />
              </div>
              </div>
            )}
          
          <div className={classes.sidebarContainer}>
            <Sidebar
              taskDescription={state.taskDescription}
              images={state.images_}
              regions={activeImage ? activeImage.regions : null}
              history={state.history}
              currentImage={activeImage}
              labelImages={state.labelImages}
              imageClsList={state.imageClsList}
              imageTagList={state.imageTagList}
              onChangeImage={action("CHANGE_IMAGE", "delta")}
              onSelectRegion={action("SELECT_REGION", "region", "source")}
              onDeleteRegion={action("DELETE_REGION", "region")}
              onSelectImage={action("SELECT_IMAGE", "image")}
              onChangeRegion={action("CHANGE_REGION", "region")}
              onRestoreHistory={action("RESTORE_HISTORY")}
              onShortcutActionDispatched={dispatch}
              changeSelectedIndex={changeSelectedIndex}
              init_idx={init_idx}
            />
          </div>
        </div>
        <SettingsDialog
          open={state.settingsOpen}
          onClose={() =>
            dispatch({
              type: "HEADER_BUTTON_CLICKED",
              buttonName: "Settings",
            })
          }
        />
      </HotkeyDiv>
    </Fullscreen>
  );
}

export default MainLayout
