import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { MdSettings, MdUndo, MdDirectionsRun } from 'react-icons/md';
import { FaFile, FaMousePointer, FaPlus, FaUndo } from 'react-icons/fa';
import { GiBrickWall, GiExitDoor, GiSteelDoor, GiWindow } from 'react-icons/gi';
import ToolbarButton from './toolbar-button';
import ToolbarSaveButton from './toolbar-save-button';
import ToolbarLoadButton from './toolbar-load-button';
import If from '../../utils/react-if';
import {
  MODE_IDLE,
  ALTERATE_STATE,
  MODE_3D_VIEW,
  MODE_3D_FIRST_PERSON,
  MODE_VIEWING_CATALOG,
  MODE_CONFIGURING_PROJECT,
} from '../../constants';
import * as SharedStyle from '../../shared-style';

import wallIcon from './image/wall2-icon-sleek-1.png'
import wallIcon2 from './image/wall2-icon-sleek-1.png'
import receptionIcon from './image/reception2-icon-sleek-1.png'
import receptionIcon2 from './image/reception2-icon-sleek-1.png'
import undoIcon from './image/undo-icon-sleek-1.png'
import undoIcon2 from './image/undo-icon-sleek-1.png'
import tickIcon from './image/done-icon-sleek-1.png'
import tickIcon2 from './image/done-icon-sleek-1.png'
import landlordIcon from './image/landlord3-icon-sleek-1.png'
import landlordIcon2 from './image/landlord3-icon-sleek-1.png'

const iconTextStyle = {
  fontSize: '19px',
  textDecoration: 'none',
  fontWeight: 'bold',
  margin: '0px',
  userSelect: 'none'
};

const iconCenterStyle = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  msTransform: 'translate(-50%, -50%)',
  transform: 'translate(-50%, -50%)',
};

const Icon2D = ( {style} ) => <p style={{...iconTextStyle, ...style}}>2D</p>;
const Icon3D = ( {style} ) => <p style={{...iconTextStyle, ...style}}>3D</p>;

const ASIDE_STYLE = {
  backgroundColor: SharedStyle.PRIMARY_COLOR.white,
  padding: '10px'
};

const sortButtonsCb = (a, b) => {
  if (a.index === undefined || a.index === null) {
    a.index = Number.MAX_SAFE_INTEGER;
  }

  if (b.index === undefined || b.index === null) {
    b.index = Number.MAX_SAFE_INTEGER;
  }

  return a.index - b.index;
};

const mapButtonsCb = (el, ind) => {
  return (
    <If
      key={ind}
      condition={el.condition}
      style={{ position: 'relative' }}
    >
      {el.dom}
    </If>
  );
};

export default class Toolbar extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      selectedToolbarIndex: -1
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    // handle area changed. deactivate drawing tool
    if (this.props.areasChanged) {
      this.setState({ selectedToolbarIndex : -1 });
      this.props.handleAreasChanged(false);
    }

    return this.props.state.mode !== nextProps.state.mode ||
      this.props.height !== nextProps.height ||
      this.props.width !== nextProps.width ||
      // this.props.state.alterate !== nextProps.state.alterate ||
      this.state.selectedToolbarIndex !== nextState.selectedToolbarIndex;
      
  }

  render() {

    let {
      props: { width, height, toolbarButtons, allowProjectFileSupport },
      context: { projectActions, viewer3DActions, translator, linesActions, holesActions, areaActions },
    } = this;

    let mode = this.props.state.get('mode');
    let alterate = this.props.state.get('alterate');
    // let alterateColor = alterate ? SharedStyle.MATERIAL_COLORS[500].orange : '';
    let scene = this.props.state.scene;
    
    let selectedToolbarIndex = this.state.selectedToolbarIndex;

    let sorter = [
      // {
      //   index: 0, condition: allowProjectFileSupport, dom: <ToolbarButton
      //     active={false}
      //     tooltip={translator.t('New project')}
      //     onClick={event => confirm(translator.t('Would you want to start a new Project?')) ? projectActions.newProject() : null}>
      //     <FaFile />
      //   </ToolbarButton>
      // },
      // {
      //   index: 1, condition: allowProjectFileSupport,
      //   dom: <ToolbarSaveButton state={state} />
      // },
      // {
      //   index: 2, condition: allowProjectFileSupport,
      //   dom: <ToolbarLoadButton state={state} />
      // },

      {
        index: 0, condition: true, 
        dom: <ToolbarButton
        active={false}
        selected={selectedToolbarIndex === 0}
        tooltip={translator.t('Draw Wall')}
        onClick={event => {
          projectActions.unselectAll();
          //check if currently selected 
          if (selectedToolbarIndex !== 0) {
            this.context.linesActions.selectToolDrawingLine('wall');
            this.setState({ selectedToolbarIndex : 0 });
          } else {
            if (mode === 'MODE_DRAWING_LINE') {
              projectActions.undo();
            }
            projectActions.setMode( MODE_IDLE );
            this.setState({ selectedToolbarIndex : -1 });
          }
        }}
        activeIcon={<img src={wallIcon} width={28} height={28} style={iconCenterStyle} alt={"wallIcon"}/>}
        inactiveIcon={<img src={wallIcon2} width={28} height={28} style={iconCenterStyle} alt={"wallIcon2"}/>}
        >
        </ToolbarButton>
      },
      {
        index: 1, condition: true, 
        dom: <ToolbarButton
        active={false}
        selected={selectedToolbarIndex === 1}
        tooltip={translator.t('Insert Reception Area')}
        onClick={event => {
          projectActions.unselectAll();

          //check if currently selected 
          if (selectedToolbarIndex !== 1) {
            this.context.holesActions.selectToolDrawingHole('door');
            this.setState({ selectedToolbarIndex : 1 });
            // console.log(mode)
          } else {
            projectActions.setMode( MODE_IDLE );
            this.setState({ selectedToolbarIndex : -1 });
          }

        }}
        activeIcon={<img src={receptionIcon} width={28} height={28} style={iconCenterStyle} alt={"receptionIcon"}/>}
        inactiveIcon={<img src={receptionIcon2} width={28} height={28} style={iconCenterStyle} alt={"receptionIcon2"}/>}
        >
        </ToolbarButton>
      },
      {
        index: 2, condition: true, 
        dom: <ToolbarButton
        active={false}
        selected={selectedToolbarIndex === 2}
        tooltip={translator.t('Toggle Landlord Areas')}
        onClick={event => {
          if (mode === 'MODE_DRAWING_LINE') {
            projectActions.undo();
          }
          projectActions.unselectAll();
          projectActions.setMode( MODE_IDLE );

          if (selectedToolbarIndex !== 2) {
            // select all areas by 2 steps
            // areas['area_id1']['selected'] = true
            // areas['area_id2']['selected'] = true
            // selected['areas'] = ['area_id1', 'area_id2']
            // find all area id and then select while in alterate state

            // bug : alternating between getting last areas and all areas 

            projectActions.setAlterateState();
            let defaultlayerID = 'layer-1'; // image layer
            let areas = scene.getIn(['layers', defaultlayerID, 'areas']); // get the areas
            let areasValues = areas.valueSeq();
            // console.log(areasValues)
            areasValues.forEach(({ id: areaID }) => {
              areaActions.selectArea(defaultlayerID, areaID);
            });            
            projectActions.setAlterateState();
            this.setState({ selectedToolbarIndex : 2 });
          } else {
            // projectActions.unselectAll();
            // projectActions.setMode( MODE_IDLE );
            this.setState({ selectedToolbarIndex : -1 });
          }
        }}
        activeIcon={<img src={landlordIcon} width={28} height={28} style={iconCenterStyle} alt={"landlordIcon"}/>}
        inactiveIcon={<img src={landlordIcon2} width={28} height={28} style={iconCenterStyle} alt={"landlordIcon2"}/>}
        >
        </ToolbarButton>
      },
      {
        index: 3, condition: true, dom: <ToolbarButton
          active={false}
          tooltip={translator.t('Undo')}
          selected={selectedToolbarIndex === 3}
          onClick={event => {
            projectActions.unselectAll();
            projectActions.undo();
            this.setState({ selectedToolbarIndex : -1 });
          }}
          activeIcon={<img src={undoIcon} width={28} height={28} style={iconCenterStyle} alt={"undoIcon"}/>}
          inactiveIcon={<img src={undoIcon2} width={28} height={28} style={iconCenterStyle} alt={"undoIcon2"}/>}
          >
        </ToolbarButton>
      },
      {
        index: 4, condition: true, dom: <ToolbarButton
          active={false}
          selected={selectedToolbarIndex === 4}
          tooltip={translator.t('Stop Editing')}
          onClick={event => {
            if (mode === 'MODE_DRAWING_LINE') {
              projectActions.undo();
            }
            projectActions.unselectAll();
            projectActions.setMode( MODE_IDLE );
            this.setState({ selectedToolbarIndex : -1 });
            // console.log(scene)
          }}
          activeIcon={<img src={tickIcon} width={28} height={28} style={iconCenterStyle} alt={"tickIcon"}/>}
          inactiveIcon={<img src={tickIcon2} width={28} height={28} style={iconCenterStyle} alt={"tickIcon2"}/>}
          >
        </ToolbarButton>
      },
      
      // {
        //   index: 3, condition: true,
        //   dom: <ToolbarButton
        //     active={[MODE_VIEWING_CATALOG].includes(mode)}
        //     tooltip={translator.t('Open catalog')}
        //     onClick={event => projectActions.openCatalog()}>
        //     <FaPlus />
        //   </ToolbarButton>
        // },
        // {
          //   index: 4, condition: true, dom: <ToolbarButton
          //     active={[MODE_3D_VIEW].includes(mode)}
          //     tooltip={translator.t('3D View')}
      //     onClick={event => viewer3DActions.selectTool3DView()}>
      //     <Icon3D />
      //   </ToolbarButton>
      // },
      // {
      //   index: 5, condition: true, dom: <ToolbarButton
      //     active={[MODE_IDLE].includes(mode)}
      //     tooltip={translator.t('2D View')}
      //     onClick={event => projectActions.setMode( MODE_IDLE )}>
      //     {[MODE_3D_FIRST_PERSON, MODE_3D_VIEW].includes(mode) ? <Icon2D style={{color: alterateColor}} /> : <FaMousePointer style={{color: alterateColor}} />}
      //   </ToolbarButton>
      // },
      // {
      //   index: 6, condition: true, dom: <ToolbarButton
      //     active={[MODE_3D_FIRST_PERSON].includes(mode)}
      //     tooltip={translator.t('3D First Person')}
      //     onClick={event => viewer3DActions.selectTool3DFirstPerson()}>
      //     <MdDirectionsRun />
      //   </ToolbarButton>
      // },
      // {
      //   index: 8, condition: true, dom: <ToolbarButton
      //     active={[MODE_CONFIGURING_PROJECT].includes(mode)}
      //     tooltip={translator.t('Configure project')}
      //     onClick={event => projectActions.openProjectConfigurator()}>
      //     <MdSettings />
      //   </ToolbarButton>
      // }
      
    ];

    // commented out to remove custom toolbar additions e.g. screenshot

    // sorter = sorter.concat(toolbarButtons.map((Component, key) => {
    //   return Component.prototype ? //if is a react component
    //     {
    //       condition: true,
    //       dom: React.createElement(Component, { mode, state, key })
    //     } :
    //     {                           //else is a sortable toolbar button
    //       index: Component.index,
    //       condition: Component.condition,
    //       dom: React.createElement(Component.dom, { mode, state, key })
    //     };
    // }));


    return (
      <aside style={{ ...ASIDE_STYLE, maxWidth: width, maxHeight: height }} className='toolbar'>
        {sorter.sort(sortButtonsCb).map(mapButtonsCb)}
      </aside>
    )
  }
}

Toolbar.propTypes = {
  state: PropTypes.object.isRequired,
  width: PropTypes.number.isRequired,
  height: PropTypes.number.isRequired,
  allowProjectFileSupport: PropTypes.bool.isRequired,
  toolbarButtons: PropTypes.array
};

Toolbar.contextTypes = {
  projectActions: PropTypes.object.isRequired,
  viewer2DActions: PropTypes.object.isRequired,
  viewer3DActions: PropTypes.object.isRequired,
  linesActions: PropTypes.object.isRequired,
  holesActions: PropTypes.object.isRequired,
  areaActions: PropTypes.object.isRequired,
  itemsActions: PropTypes.object.isRequired,
  translator: PropTypes.object.isRequired,
};
