/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  StatusBar,
  SafeAreaView,
  Platform,
  Alert,
  Clipboard,
} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import firebase from 'react-native-firebase';

const setBadgesCount = badgeCount => {
  badgeCount = Number.isInteger(Number.parseInt(badgeCount, 10))
    ? Number.parseInt(badgeCount, 10)
    : 0;
  firebase.notifications().setBadge(badgeCount);
};

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  async componentDidMount() {
    if (Platform.OS === 'ios') {
      try {
        console.info('Notification[deviceToken] init');
        await firebase.messaging().ios.registerForRemoteNotifications();
        console.info('Notification[deviceToken] to do requestPermission');
        await firebase.messaging().requestPermission();
        const deviceToken = await firebase.messaging().ios.getAPNSToken();
        console.info(`Notification[deviceToken] ${deviceToken}`);
        Alert.alert('getAPNSToken', deviceToken, [
          {
            text: 'ok',
            onPress: async () => {
              await Clipboard.setString(deviceToken);
            },
          },
        ]);
      } catch (e) {
        console.error('Notification[registerForRemoteNotifications] error:', e);
      }
    } else {
      try {
        console.info('Notification[deviceToken] init');
        const enabled = await firebase.messaging().hasPermission();
        if (!enabled) {
          await firebase.messaging().requestPermission();
        }
        const deviceToken = await firebase.messaging().getToken();
        console.info(`Notification[deviceToken] ${deviceToken}`);
      } catch (e) {
        console.error('Notification[requestPermission] error:', e);
      }
    }
    this.registerNotifications();
  }

  componentWillUnmount() {
    // Unsubscribe
    if (this.notificationDisplayedListener) {
      this.notificationDisplayedListener();
    }
    if (this.notificationListener) {
      this.notificationListener();
    }
    if (this.notificationOpenedListener) {
      this.notificationOpenedListener();
    }
    // if (this.messageListener) this.messageListener();
  }

  async registerNotifications() {
    /*
     * Triggered when a particular notification has been received in foreground
     * */
    this.notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        console.info('Notification[onNotification]', notification);
        const {_body, _data} = notification;
        if (_data) {
          const {badge, pushId} = _data;
          if (pushId) {
            if (badge) {
              setBadgesCount(badge);
            }
            this.handleNotification({
              badge,
              pushId,
              body: _body,
              foreground: true,
            });
          } else {
            console.error(
              'Notification[onNotification]: No Notification PushId',
            );
          }
        } else {
          console.error('Notification[onNotification]: No Notification Body');
        }
      });

    /*
     * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
     * */
    this.notificationOpenedListener = firebase
      .notifications()
      .onNotificationOpened(notificationOpen => {
        console.info('Notification[onNotificationOpened]', notificationOpen);
        const {_body, _data} = notificationOpen.notification;
        if (_data) {
          const {badge, pushId} = _data;
          if (pushId) {
            this.handleNotification({
              badge,
              pushId,
              body: _body,
              userInteraction: true,
            });
          } else {
            console.error(
              'Notification[onNotificationOpened]: No Notification PushId',
            );
          }
        } else {
          console.error(
            'Notification[onNotificationOpened]: No Notification Body',
          );
        }
      });

    /*
     * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
     * */
    const notificationOpen = await firebase
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      console.info('Notification[notificationOpen]', notificationOpen);
      const {_body, _data} = notificationOpen.notification;
      if (_data) {
        const {badge, pushId} = _data;
        if (pushId) {
          this.handleNotification({
            badge,
            pushId,
            body: _body,
            userInteraction: true,
          });
        } else {
          console.error(
            'Notification[notificationOpen]: No Notification PushId',
          );
        }
      } else {
        console.error('Notification[notificationOpen]: No Notification Body');
      }
    }

    this.notificationDisplayedListener = firebase
      .notifications()
      .onNotificationDisplayed(notification => {
        // Process your notification as required
        // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
        console.info('Notification[onNotificationDisplayed]', notification);
      });

    /*
     * Triggered for data only payload in foreground
     * */
    // this.messageListener = firebase.messaging().onMessage(message => {
    //   // process data message
    //   console.info('Notification[onMessage]', JSON.stringify(message));
    // });
  }

  /**
   * 處理推播訊息通知
   * @param {Object} notification
   */
  handleNotification(notification) {
    console.info(`handleNotification: ${JSON.stringify(notification)}`);
    const {body} = notification;
    Alert.alert('', body, [{text: 'ok'}]);
  }

  render() {
    return (
      <View style={styles.scrollView}>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView style={styles.body}>
          <Text style={styles.sectionTitle}>sample react native </Text>
        </SafeAreaView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
});

export default App;
