import React from 'react';
import { Button } from 'react-native';
import { WebView } from 'react-native-webview';

export default class LinkedInWebView extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    headerLeft: null,
    headerRight: <Button title="Done" onPress={() => navigation.goBack()} />
  });

  /**
   * This the bridge connecting the WebView and ReactNative. The data you see here is sent by postMessage from
   * within the DOM in the WebView.
   */
  onComplete(data) {
    const result = JSON.parse(data);
    if (result) {
      this.props.navigation.state.params.onSuccess(result);
    }
    this.props.navigation.goBack();
  }

  render() {
    return (
      <WebView 
        source={{ uri: this.props.navigation.state.params.result.uri }}
        onMessage={(event) => this.onComplete(event.nativeEvent.data)}
      />
    );
  }
}
