/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */

import React from 'react';
// import { Notifications } from 'expo';
import * as Notifications from 'expo-notifications';
import * as Permissions from 'expo-permissions';

import Constants from 'expo-constants';
import {
  Text,
  View,
  StyleSheet,
  Dimensions,
  KeyboardAvoidingView,
} from 'react-native';
import { Container, Content, Button } from 'native-base';
import HeaderCommon from '../../components/common/header';
import { NavigationDrawerScreenProps } from 'react-navigation-drawer';
import InputBlock from '../../components/firebase/InputBlock';
import * as Font from 'expo-font';
const YOUR_PUSH_TOKEN = 'YOUR_PUSH_TOKEN';
const keyboardOffSetAndroid = Constants.platform
  ? Constants.platform.android
    ? Dimensions.get('screen').height -
    Dimensions.get('window').height -
    Constants.statusBarHeight
    : 0
  : null;

interface Iprops extends NavigationDrawerScreenProps { }
export default class PushNotificationExample extends React.Component<Iprops> {
  state = {
    notification: null,
    notifications: [],
    title: '',
    body: '',
    notificationData: '',
    token: '',
    fontLoaded: false,
  };
  _notificationSubscription: any = '';
  toggleMenu = () => this.props.navigation.toggleDrawer();
  registerForPushNotificationsAsync = async () => {
    if (Constants.isDevice) {
      const { status: existingStatus } = await Permissions.getAsync(
        Permissions.NOTIFICATIONS
      );
      let finalStatus = existingStatus;
      if (existingStatus !== 'granted') {
        // only ask if permissions have not already been determined, because
        // iOS won't necessarily prompt the user a second time.
        // Android remote notification permissions are granted during the app
        // install, so this will only ask on iOS
        const { status } = await Permissions.askAsync(
          Permissions.NOTIFICATIONS
        );
        finalStatus = status;
      }
      if (finalStatus !== 'granted') {
        alert('Failed to get push token for push notification!');
        return;
      }
      // Get the token that uniquely identifies this device
      const token = (await Notifications.getExpoPushTokenAsync()).data;

      // POST the token to your backend server from where you can retrieve it to send push notifications.
      this.setState({
        token,
      });
      return;
    } else {
      alert('Must use physical device for Push Notifications');
    }
  };

  async componentDidMount() {
    // Permissions.askAsync(Permissions.NOTIFICATIONS).then(status => {
    //     if (status === 'granted') {

    //     }
    // });
    this.registerForPushNotificationsAsync();

    // Handle notifications that are received or selected while the app
    // is open. If the app was closed and then opened by tapping the
    // notification (rather than just tapping the app icon to open it),
    // this function will fire on the next tick after the app starts
    // with the notification data.
    this._notificationSubscription = Notifications.addNotificationReceivedListener(
      (notification) => {
        console.log(notification);
        this.setState({ notification });
      }
    );
    await Font.loadAsync({
      montserrat: require('../../assets/Fonts/Montserrat.ttf'),
    });
    this.setState({ fontLoaded: true });
  }

  // _handleNotification = (notification: any) => {
  //   let { notifications } = this.state;
  //   notifications.push(notification);
  // };

  // Can use this function below, OR use Expo's Push Notification Tool-> https://expo.io/dashboard/notifications
  sendPushNotification = async () => {
    const { title, body, notificationData } = this.state;
    const message = {
      to: this.state.token,
      sound: 'default',
      title: title ? title : 'Original Title',
      body: body ? body : 'And here is the body!',
      data: { data: notificationData ? notificationData : 'goes here' },
    };
    await fetch('https://exp.host/--/api/v2/push/send', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Accept-encoding': 'gzip, deflate',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(message),
    });
    // const data = response._bodyInit;
    // console.log(`Status & Response ID-> ${data}`);
  };
  onChangeText = (name: string, value: string) =>
    this.setState({
      [name]: value,
    });

  render() {
    const {
      notifications,
      title,
      body,
      notificationData,
      fontLoaded,
    } = this.state;
    if (!fontLoaded) {
      return <Container></Container>;
    }
    return (
      <Container>
        <HeaderCommon title="Push Notifications" toggleMenu={this.toggleMenu} />
        <KeyboardAvoidingView
          style={styles.KeyboardAvoidingView}
        >
          <Content scrollEnabled={true}>
            <Text style={styles.paragraph}>
              For sending push notification to device, we are using notification
              API from react-native. We collect token of your device and
              send it to your device using Expo Api{' '}
            </Text>
            <Text style={styles.paragraph}>
              Push notifications have to come from somewhere, and that somewhere
              is your server (you could write a command line tool to
              send them if you wanted, it's all the same). When you're ready to
              send a push notification, grab the Expo push token of the user
              and send it over to the Expo API using a plain old HTTPS
              POST request. Expo have taken care of wrapping that for you in a
              few languages:
            </Text>
            <Text style={styles.paragraph}>
              Or you can also use Expo's Push Notification Tool
            </Text>

            <View>
              <View style={styles.notificationWrapper}>
                <Text style={styles.paragraph}>
                  Title: {this.state.notification && this.state.notification.request.content.title}
                </Text>
                <Text style={styles.paragraph}>
                  Data: {this.state.notification && JSON.stringify(this.state.notification.request.content.data)}
                </Text>
                <Text style={styles.paragraph}>
                  Body: {this.state.notification && this.state.notification.request.content.body}
                </Text>
              </View>
              <InputBlock
                name="body"
                onChangeText={(value) => this.onChangeText('body', value)}
                value={body}
                type="text"
              />
              <InputBlock
                name="title"
                onChangeText={(value) => this.onChangeText('title', value)}
                value={title}
                type="text"
              />
              <InputBlock
                name="notificationData"
                onChangeText={(value) =>
                  this.onChangeText('notificationData', value)
                }
                value={notificationData}
                type="text"
              />
              <Button
                style={styles.buttonStyle}
                onPress={() => this.sendPushNotification()}
              >
                <Text style={{ ...styles.paragraph, ...styles.white }}>
                  Press to Send Notification
                </Text>
              </Button>
            </View>
          </Content>
        </KeyboardAvoidingView>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  container: { padding: 20 },
  paragraph: {
    fontFamily: 'montserrat',
    margin: 10,
    fontSize: 18,
    textAlign: 'center',
    color: '#34495e',
  },
  KeyboardAvoidingView: {
    flex: 1,
  },
  buttonStyle: {
    width: '100%',
    justifyContent: 'center',
  },
  white: {
    color: 'white',
  },
  notificationWrapper: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'black',
  },
});
