import React from 'react';
import {Card, CardActions, CardText, CardTitle, Divider, Paper,RaisedButton, TextField,Dialog,FlatButton,} from 'material-ui';
import {inject, observer} from 'mobx-react';
import * as firebase from "firebase";
import './style.scss'
import {LINKS} from "../../routes";
import {getMobileOperatingSystem} from '../../stores/firebase';
import {Helmet} from "react-helmet";


@inject('appstate')
@observer
export default class LoginComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      email: "",
      password: "",
      warningLogin : false,
      warningLoginMessage  : '',
      notif:false,
    };
    this.defaultState = Object.assign({}, this.state);
    this.authStore = props.appstate.auth;
    this.http = props.appstate.http;
    this.settingStore = props.appstate.setting;
  }

  componentDidMount() {
    this.settingStore.getAll();
    const firebase = require('firebase');
    firebase.messaging().requestPermission()
      .then(function () {
        console.log('Notification permission granted.');
        return firebase.messaging().getToken();
      })
      .then(currentToken => {
        if (currentToken) {
          console.log(currentToken, "user tokens");
          localStorage.setItem('tokens', currentToken);
        } else {
          // Show permission request.
          console.log('No Instance ID token available. Request permission to generate one.');
          // Show permission UI.
        }
      });
  }

  handleTextFieldChange = (event, name) => {
    this.setState({
      [name]: event.target.value
    });
  };

  login=(e)=>{
    firebase.messaging().requestPermission()
    .then(() => {
        // alert('bisa')

    //     e.preventDefault();
    var tokenNotif = localStorage.getItem('tokens');
    this.authStore.login({
      username: this.state.email,
      password: this.state.password,
      firebase_token: tokenNotif
    })
      .then(() => {
        localStorage.setItem('isLoggedIn', true);
        this.props.history.push(LINKS.DASHBOARD);
        console.log(this.state.email + " is logging in..")
      }).catch(err => {
        console.log(err);
        this.openWarningMessage(err.message); 
      });

    })
    .catch(error => {
      this.setState({
        notif:true
      })
      // alert('gk bisa')  
    })

    
  }

  openWarningMessage = (message)=>{
    this.setState({
      warningLoginMessage : message,
      warningLogin : true
    })
  }

  closeWarning = ()=>{
    this.setState({
      warningLogin : false
    })
  }

  handleClose = ()=>{
    this.setState({
      notif : false
    })
  }

  render() {

    const actions = [
      <RaisedButton
        label={"Ok"}
        primary={true}
        onClick={()=>this.closeWarning()}
      />,
    ];

    const actionsNotif = [
      <RaisedButton
        label="Done"
        primary={true}
        onClick={this.handleClose}
      />,
    ];

    // const applicationIcon = (this.settingStore.isIconEmpty) ? "/assets/images/logo_ikan.png" : this.http.appendImagePath(this.settingStore.setting.icon);
    const applicationIcon = "/assets/images/logo_ikan.png";
    return (
      <div className="login login-wrapper">
        <Helmet>
          <meta charSet="utf-8"/>
          <title>{/*(this.settingStore.setting.name) ? this.settingStore.setting.name : ""*/'Marketplace'}</title>
          <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
          <link rel="icon" type="image/png" href={applicationIcon} sizes="96x96"/>
        </Helmet>
        <div style={{width: "100%"}}>
          {/*
            (this.settingStore.isIconEmpty) ?
              <div style={{textAlign: "center"}}>
                <Paper style={{
                  backgroundSize: "contain",
                  backgroundClip: "padding-box",
                  padding: 10,
                  height: 75, width: 75,
                  background: '#fff',
                  marginRight: "auto",
                  marginLeft: "auto"
                }} zDepth={1} circle={true}>
                  <img className="logo" src="/assets/images/logo_ikan.png"/>
                </Paper>
                <h2 style={{
                  color: '#000',
                  marginRight: "auto",
                  marginLeft: "auto",
                  maxWidth: 500,
                  marginTop: 15,
                  marginBottom: 0
                }}>5 Roti dan 2 Ikan</h2>
              </div>
              :
              <div style={{textAlign: "center"}}>
                <Paper style={{
                  backgroundSize: "contain",
                  backgroundClip: "padding-box",
                  padding: 10,
                  height: 75, width: 75,
                  background: '#fff',
                  marginRight: "auto",
                  marginLeft: "auto"
                }} zDepth={1} circle={true}>
                  <img className="logo"
                       src={this.http.appendImagePath(this.settingStore.setting.icon)}/>
                </Paper>
                <h2 style={{
                  color: '#275164',
                  marginRight: "auto",
                  marginLeft: "auto",
                  maxWidth: 500,
                  marginTop: 15,
                  marginBottom: 0
                }}>{this.settingStore.setting.name}</h2>
              </div>
              */
          }
          <div style={{textAlign: "center"}}>
                <Paper style={{
                  backgroundSize: "contain",
                  backgroundClip: "padding-box",
                  padding: 10,
                  height: 75, width: 75,
                  background: '#fff',
                  marginRight: "auto",
                  marginLeft: "auto"
                }} zDepth={1} circle={true}>
                  <img className="logo" src={applicationIcon}/>
                </Paper>
                <h2 style={{
                  color: '#000',
                  marginRight: "auto",
                  marginLeft: "auto",
                  maxWidth: 500,
                  marginTop: 15,
                  marginBottom: 0
                }}>Marketplace</h2>
              </div>
        </div>
        <Card style={{width: 350, marginTop: '18px'}} className="cardLite align-center">
          <CardTitle title={<p style={{fontSize: 14}}>Login to Store Admin Console</p>}>
            <Divider style={{backgroundColor: 'rgba(171, 111, 48, 1)', width: '150px'}} className="margin-auto"/>
          </CardTitle>

          <form>
            <CardText>
              <TextField
                hintText="Email"
                fullWidth={true}
                name="email"
                type="email"
                value={this.state.email}
                onChange={(event) => this.handleTextFieldChange(event, 'email')}
              />
              <TextField
                hintText="Password"
                name="password"
                fullWidth={true}
                type="password"
                value={this.state.password}
                onChange={(event) => this.handleTextFieldChange(event, 'password')}
                onKeyPress={(ev) => {
                  if (ev.key === 'Enter') {
                    // Do code here
                    this.login()
                  }
                }}
              />
            </CardText>
            <CardActions>
              <RaisedButton primary={true} label="Login To Your Account" onClick={this.login}/>
            </CardActions>
            <a style={{fontSize: 12, fontWeight: 500, display: 'block', margin: '18px 0px 30px'}}
               onClick={() => this.props.history.push(LINKS.FORGOT_PASSWORD)}>Forgot Password</a>
          </form>
        </Card>
        <Dialog
          title="Error"
          actions={actions}
          modal={true}
          open={this.state.warningLogin}
          onRequestClose={() => this.closeWarning()}
        >
          {this.state.warningLoginMessage}
        </Dialog>
        <Dialog
          title="Warning"
          actions={actionsNotif}
          open={this.state.notif}
          autoScrollBodyContent={true}
          modal={false}
        >
            <p>1. You must allow notification</p>
            <div style={{textAlign:'center'}}>
              <img src="/assets/images/notification.jpg" style={{height : '400px'}}/>
            </div>
            <p style={{marginTop:'1em'}}>2. Reload Page</p>
            <div style={{textAlign:'center'}}>
              <img style={{height: "400px"}}  src="/assets/images/reload.jpg"/>
            </div>
            {/*<p>1. You must allow notification</p>
                        <img style={{width: "100%", height: "100%"}}  src="/assets/images/notification.jpg"/>*/}
        </Dialog>
      </div>
    )
  }
}
