/*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, useState, useEffect } from 'react'
import axios from 'axios'
import {apiUrl} from '../env'
import MenuBar from './MenuBar'
import SearchBar from './SearchBar'
import SignUpModal from './SignUpModal'
import LoginModal from './LoginModal.js'
import { Store } from '../Store';
import ColaborarModal from './ColaborarModal.js'
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';
import {useLocation} from 'react-router-dom'
import MenuBarMobile from './MenuBarMobile.js'

//const StyledButton = styled(Button)`
//    background : #ffa54c !important;
//    boxShadow :none;
//`
function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}


export default function Header(props){
  const { state, dispatch } = useContext(Store)
  const [signUpOpen, setSignUp] = useState(false)
  const [loginOpen, setLogin] = useState(false)
  const [successfulLoginOpen, handleSuccessfulLogin] = useState(false)
  const [modalColaborar, setModalColaborar] = useState(false)

  const validateToken = (config) => {
      axios.get(`${apiUrl}/auth/validate_token/`, config).then(
           (response) => {
              console.log(response.data)
              if ( response.headers['access-token'] ) {
                  sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token'])
              }
              dispatch ({
                  type: "USER_LOGGED_IN",
                  userLoggedIn: !state.userIsLoggedIn,
                  login: response.data.data
                  }
              )

              sessionStorage.setItem('@portalmec/id', response.data.data.id)
              sessionStorage.setItem('@portalmec/username', response.data.data.name)
              sessionStorage.setItem('@portalmec/uid', response.data.data.uid)


              let headers = {
                  client:response.headers.client,
                  "access-token":response.headers['access-token'],
                  "token-type": "Bearer",
                  expiry:response.headers.expiry,
                  uid:response.data.data.uid
              }
              sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(headers))
          },
          (err) => {
              console.log(err)
          }
       )
  }

  useEffect( () => {
      if (sessionStorage.getItem('@portalmec/auth_headers')) {
          let config = { headers : JSON.parse(sessionStorage.getItem('@portalmec/auth_headers'))}
          console.log(config)
          console.log(sessionStorage.getItem('@portalmec/accessToken'))

          if (config.headers['access-token'] !== sessionStorage.getItem('@portalmec/accessToken')){
              console.log('erro tokens diferentes')
          }
          validateToken(config)
      }
  }, [])

  useEffect ( () => {
      if (state.currentUser.askTeacherQuestion === true) {
          dispatch({
            type: "TOGGLE_MODAL_COLABORAR_PLATAFORMA",
            modalColaborarPlataformaOpen: true
          });
      }
  }, [state.currentUser.askTeacherQuestion])

  const redirect = () => {
      props.history.push('/')
  }

  let loc = useLocation()
  useEffect(() => {
      let query = new URLSearchParams(loc.search)

      console.log(query.getAll("auth_token"))
      if(query.get("auth_token")) {
  	       let config = {
  		           headers : {
  			                  "access-token" : query.get("auth_token"),
  			                  "client" : query.get("client_id"),
  			                  "uid" : query.get("uid"),
  			                  "expiry" : query.get("expiry"),
  			                  "token-type" : 'Bearer'
  		           }
  	            }
  	       validateToken(config)
           redirect()
      }
  }, [loc])

  const toggleSnackbar = (event, reason) => {
      if (reason === 'clickaway') {
          return;
      }

      handleSuccessfulLogin(false);
  }

  const handleSignUp = () => {
      setSignUp(!signUpOpen)
  }

  const handleLogin = () => {
      setLogin(!loginOpen)
  }

  const handleClickSearch = (open) => {
    dispatch({
      type: "HANDLE_SEARCH_BAR",
      opened: !state.searchOpen
    })
  }

  let windowWidth = window.innerWidth

  return (
    <React.Fragment>
       {/*
           windowWidth > 990 &&
           <AcessibilityBar/>
       */}
        <Snackbar open={successfulLoginOpen} autoHideDuration={1000} onClose={toggleSnackbar}
                  anchorOrigin = {{ vertical:'top', horizontal:'center' }}
              >
              <Alert severity="success" style={{backgroundColor:"#00acc1"}}>Você está conectado(a)!</Alert>
        </Snackbar>
        {
            windowWidth > 990 ?
            (
                <React.Fragment>
                    <MenuBar openSearchBar={handleClickSearch} openSignUp = {handleSignUp} openLogin = {handleLogin}/>
                    {
                    state.searchOpen &&
                    <SearchBar/>
                    }
                </React.Fragment>

            )
            :
            (
                <MenuBarMobile openSignUp = {handleSignUp} openLogin = {handleLogin}/>
            )
        }
      <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin}/>
      <LoginModal open={loginOpen} handleClose={() => setLogin(false)}      openSignUp={handleSignUp}
                  openSnackbar={() => {handleSuccessfulLogin(true)}}/>
      <ColaborarModal open={modalColaborar} handleClose={() => {setModalColaborar(!modalColaborar)}} />
    </React.Fragment>
  )
}