import React, { Component } from 'react';
import { StyleSheet, Text, View, WebView } from 'react-native';

import { connect } from 'redux-su';
import { getBottomSpace, getStatusBarHeight } from '../helper';
import actions from '../Actions/actions';

const LOGIN_URL = "https://accounts.google.com/ServiceLogin?service=ah&passive=true&continue=https://appengine.google.com/_ah/conflogin%3Fcontinue%3Dhttps://intel.ingress.com/";
const HOME_URL = "https://intel.ingress.com/";

type Props = {
    login(): void
    actions: any
    auth: any
}

type State = {
    onIngress: boolean
}

class Login extends Component<Props, State> {
    webview!: WebView;
    constructor(props: Props) {
        super(props);
        this.state = { onIngress: false }
    }

    onNavigationStateChange(navState: WebViewNavigation) {
        if (navState.url == HOME_URL) {
            this.setState({ onIngress: true })
            this.props.actions.login()
        }
    }

    renderLogin() {
        if (this.state.onIngress) {
            return (<Text>Пожалуйста, подождите...</Text>);
        }
        return (
            <>
                <WebView
                    ref={r => r && (this.webview = r)}
                    automaticallyAdjustContentInsets={true}
                    thirdPartyCookiesEnabled
                    useWebKit
                    style={styles.container}
                    source={{ uri: LOGIN_URL }}
                    javaScriptEnabled={true}
                    onNavigationStateChange={this.onNavigationStateChange.bind(this)}
                    startInLoadingState={true}
                />
            </>
        );
    }

    render() {
        return (<View style={{ flexGrow: 1, paddingTop: getStatusBarHeight(true), paddingBottom: getBottomSpace() }}>
            {this.renderLogin()}
        </View>);
    }
}

var styles = StyleSheet.create({
    container: {
        flex: 1,
    }
});


export default connect({ 'auth': 'auth' }, actions)(Login)