import { WebviewTag } from 'electron';
import * as _ from 'lodash';
import { inject, observer } from 'mobx-react';
import React from 'react';
import { POE_HOME } from '../../constants';
import { AppStore } from '../../stores/app.store';

interface IProps {
  appStore?: AppStore;
}

@inject('appStore')
@observer
export class LoginWebview extends React.Component<IProps, any> {
  private webview: WebviewTag;

  constructor(props: IProps) {
    super(props);
  }

  componentDidMount() {
    this.webview = this.refs['webview'] as any;
    this.webview.addEventListener('did-stop-loading', this.didStopLoading);
  }

  // if webview redirect to my-account - means user logged in
  didStopLoading = (event: any) => {
    if ((event.target.src as string).includes('my-account')) {
      this.getCookies();
    }
  };

  // get cookies from login and store username/sessionID
  getCookies() {
    const session = this.webview.getWebContents().session;
    session.cookies.get({ url: POE_HOME }, async (error, cookies) => {
      if (error) {
        console.error(error);
        return;
      }
      try {
        const cookie: any = _.find(cookies, c => c.name === 'POESESSID');
        this.props.appStore!.performLogin(cookie.value);
      } catch (e) {
        this.props.appStore!.resetState();
      }
    });
  }

  render() {
    return <webview ref="webview" src={`${POE_HOME}/login`} style={{ height: '100%', width: '100%' }} />;
  }
}
