/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana

This file is part of Plataforma Integrada MEC.

Plataforma Integrada MEC is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Plataforma Integrada MEC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Plataforma Integrada MEC.  If not, see <http://www.gnu.org/licenses/>.*/

import React, {useContext} from 'react';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import { Link } from 'react-router-dom'
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import { Store } from '../Store';
import Profile from '../img/default_profile0.png'
import styled from 'styled-components'
import {apiDomain, apiUrl} from '../env.js'
import {getAxiosConfig} from './HelperFunctions/getAxiosConfig'
import axios from 'axios'


const OverrideButton = styled(Button)`
    text-transform : none !important;
`

export default function MenuList(props) {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const { state, dispatch } = useContext(Store)

  const handleClick = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLogout = () => {
      let config = getAxiosConfig()
      axios.delete(`${apiUrl}/auth/sign_out`, config).then(
          () => {

          localStorage.removeItem('@portalmec/username');
          sessionStorage.removeItem('@portalmec/uid');
          sessionStorage.removeItem('@portalmec/senha');
          dispatch( {
              type: 'USER_LOGGED_OUT',
              userLoggedOut: !state.userIsLoggedIn,
              login: {
                  username : '',
                  email : '',
                  accessToken : '',
                  client : ''
              }
          })
      },
      (err) => {
          console.log(err)
      }
      )

  }

  return (
    <div >

      <OverrideButton
        aria-controls="customized-menu"
        aria-haspopup="true"
        onMouseEnter={handleClick}

      >
        <div style={{borderRadius: "50%", border: "2px solid #fff", background: "#fff", overflow: "hidden", maxWidth : "50px", maxHeight : "50px"}}>
            {
                state.currentUser.avatar_file_name === '' || state.currentUser.avatar_file_name === null ?
                (

                    <img src={Profile} alt={'user avatar'} style={{width:"100%", height:"100%", verticalAlign : "middle", marginLeft : "0"}}/>
                ):
                (
                    <img src={apiDomain + state.currentUser.avatar_file_name} alt={'user avatar'} style={{width:"100%", height:"100%", verticalAlign : "middle", marginLeft : "0"}}/>
                )
            }
        </div>
            <span style={{fontFamily:"inherit", fontWeight:"400", color:"#666"}}>Minha Área </span> <KeyboardArrowDownIcon/>
      </OverrideButton>

      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleClose}
        elevation={0}
        getContentAnchorEl={null}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'center',
      }}>

        {
          props.items.map((item)=>
            <Link  to={{
                pathname : item.href,
                state : item.value
            }} style={{textDecoration:"none"}} key={item.value}><MenuItem style= {{fontSize:"14px", padding:"5px 20px", color:"#666"}} key={item.value}>{item.name}</MenuItem></Link>
        )
        }
        <StyledButtonSair onClick={handleLogout}> <StyledMenuItem disableGutters={true}>Sair<StyledExitToAppIcon/></StyledMenuItem></StyledButtonSair>


      </Menu>
    </div>
  );
}

const StyledButtonSair = styled(Button)`
    height : 31px;
    width : 177px;
    layout : row;

    .listItem {
        width : 100% !important;
        display : flex !important;
        justify-content: space-between !important;
        font-size : 14px !important;
        color : #a5a5a5 !important;
        padding : 5px 20px !important;
    }
`

const StyledExitToAppIcon = styled(ExitToAppIcon) `
    fontSize : 24px;
    color : rgb(162,165,165);
    align : right;
    display : flex;
    justify-content : flex-end;
`
const StyledMenuItem = styled(MenuItem)`
    display : flex !important;
    justify-content: space-between !important;
    width : 100% !important;
    font-size : 14px !important;
    color : #a5a5a5 !important;
    padding : 5px 20px !important;
`

//import React from 'react';
//import Button from '@material-ui/core/Button';
//import ClickAwayListener from '@material-ui/core/ClickAwayListener';
//import Grow from '@material-ui/core/Grow';
//import Paper from '@material-ui/core/Paper';
//import Popper from '@material-ui/core/Popper';
//import MenuItem from '@material-ui/core/MenuItem';
//import MenuList from '@material-ui/core/MenuList';
//import { makeStyles } from '@material-ui/styles';
//import AccountCircleRoundedIcon from '@material-ui/icons/AccountCircleRounded';
//import styled from 'styled-components'
//import {BrowserRouter, Switch, Route} from 'react-router-dom';
//
//const iconStyles = {
//    fontSize : "xxx-large",
//    color: "white",
//    backgroundColor: "gray",
//    borderRadius : "50%",
//    overflow : "hidden",
//    border : "2px solid #fff",
//}
//
//export default function MenuListComposition(props) {
//  const [open, setOpen] = React.useState(false);
//  const anchorRef = React.useRef(null);
//
//  const handleToggle = () => {
//    setOpen(prevOpen => !prevOpen);
//  };
//
//  const handleClose = event => {
//    if (anchorRef.current && anchorRef.current.contains(event.target)) {
//      return;
//    }
//
//    setOpen(false);
//  };
//
//  function handleListKeyDown(event) {
//    if (event.key === 'Tab') {
//      event.preventDefault();
//      setOpen(false);
//    }
//  }
//
//  // return focus to the button when we transitioned from !open -> open
//// const prevOpen = React.useRef(open);
////  React.useEffect(() => {
////    if (prevOpen.current === true && open === false) {
////      anchorRef.current.focus();
////    }
////
////    prevOpen.current = open;
////  }, [open]);
//
//  return (
//    <div style={{minWidth:"212px"}}>
//      <div>
//      <Button
//        ref={anchorRef}
//        aria-controls={open ? 'menu-list-grow' : undefined}
//        aria-haspopup="true"
//        onMouseOver={handleToggle}>
//      <AccountCircleRoundedIcon style={iconStyles}/>
//        Minha Área
//      </Button>
//        <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
//          {({ TransitionProps, placement }) => (
//            <Grow
//              {...TransitionProps}
//              style={{ transformOrigin: placement = 'bottom'}}
//            >
//              <Paper>
//                <ClickAwayListener onClickAway={handleClose}>
//                  {
//                      props.items.map((item)=>
//                        <Route path={item.href} ><MenuItem>{item.name}</MenuItem></Route>
//                    )
//                }
//                </ClickAwayListener>
//              </Paper>
//            </Grow>
//          )}
//        </Popper>
//      </div>
//    </div>
//
//  );
//}
//