import React from 'react';
import { Button, Menu, MenuItem} from '@material-ui/core';
import { Popover, OverlayTrigger } from 'react-bootstrap';

class AppSelector extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showAppSelector: false,
      anchorEl: null,
      selectedIndex: 0,
    };
  }

  selectApp(appId, index) {
    if (appId) this.props.selectApp(appId);
    this.setState({ showAppSelector: false, selectedIndex: index, anchorEl: null });
  }

  handleChange = (event, index, value) => this.setState({value});

  setImgFallbackUrl(e) {
    e.target.onError = null;
    e.target.src = this.props.imgFallbackURL;
  }

  setAnchorEl(e) {
    this.setState({ anchorEl: e.currentTarget })
  }

  handleClose() {
    this.setState({ anchorEl: null });
  }

  render() {
    const allApps = this.props.apps.map((app, i) => {
      const label = (
          <div className="app-selector-item">
              <img height="25px" width="25px"
                   className="app-selector-img"
                   src={this.props.imgFallbackURL}
                  //  onError={this.setImgFallbackUrl.bind(this)}
                   style={{marginBottom: 3}}
              />
              <span style={{ fontSize: 16 }}>{app.name}</span>
          </div>
      );

      let thisObj = this;
      return (
          <MenuItem
              className={app.appId === thisObj.props.currentApp ? 'selected-app app-list-item' : 'app-list-item'}
              key={i}
              onClick={this.selectApp.bind(this, app.appId, i)}>
              {label}
          </MenuItem>
      );
    });
    let value = 0;
    if (this.props.apps) {
        value = _.findIndex(this.props.apps, ['appId', this.props.currentApp]);
    }
    return (
      <div>
        <Button className="app-selector" onClick={this.setAnchorEl.bind(this)}>
          <img 
            height="20px"
            className="app-selector-img"
            src={this.props.imgFallbackURL}
            // onError={this.setImgFallbackUrl.bind(this)}
          />
          <span className="app-selector-current">{this.props.currentAppName}</span>
          <svg
            viewBox="0 0 24 24"
            style={{marginLeft: 5, userSelect: 'none', display: 'inline-block', color: 'gray !important', fill: '#dcd8d8', height: '24px', width: '24px', transition: 'all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms'}}>
            <path d="M7 10l5 5 5-5z"></path>
          </svg>
        </Button>
        <Menu 
          open={Boolean(this.state.anchorEl)}
          anchorEl={this.state.anchorEl}
          onClose={this.handleClose.bind(this)}
          value={value}
          onChange={this.handleChange.bind(this)}
          className="app-selector-menu"
        >
          {allApps}
        </Menu>
      </div>
    );
  }
}

export default AppSelector;
