import React, { Component } from 'react';
import { View, Text, StyleSheet, Clipboard, Platform } from 'react-native';
import Button from '../../components/Button';
import PushNotification from "react-native-push-notification";
import Dialog from '../../components/Dialog';
import apiUpload from '../../api/apiUpload';
import app from '../../../app.json'
import utils from '../../utils/utils';

export default class Notify extends Component {
  constructor(props) {
    super(props);
    this.state = {
      permission: false,
      notifyToken: '',
      serverToken: ''
    };
  }

  componentDidMount() {
    //this.requestUserPermission()
    if (global.notifyToken.token) {
      this.setState({
        notifyToken: global.notifyToken.token
      })
    }
    this.getUserToken();
  }

  getUserToken() {
    getUserInfo(info => {
      if (info.firebaseToken) {
        let token = isIOS ? info.firebaseToken?.ios : info.firebaseToken?.android
        this.setState({
          serverToken: token ?? ""
        });
      }
    }, true);
  }

  async requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    this.setState({
      permission: enabled
    })
    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
    this.getToken()
  }

  getToken() {
    messaging().getToken().then(token => {
      if (token) {
        this.setState({
          notifyToken: token
        })
        console.log("token", token);
      }
    }).catch(err => {
      console.info('Token Error', err)
    });
  }

  localNotification() {
    PushNotification.localNotification({
      /* Android Only Properties */
      channelId: "10186", // (required) channelId, if the channel doesn't exist, notification will not trigger.
      showWhen: true, // (optional) default: true
      autoCancel: true, // (optional) default: true
      title: app.displayName, // (optional) default: "message" prop
      message: "This is a local test message", // (optional) default: none
      vibrate: true, // (optional) 振动开关default: true
      vibration: 300, // 振动长度（毫秒），如果vibrate=false，则忽略, default: 1000
      invokeApp: true, // 此选项允许单击操作将应用程序带回前台或留在后台, default: true
      smallIcon: "ic_notification",
      /* iOS only properties */
      //subtitle: "My Notification Subtitle", // (optional) smaller title below notification title
    });
  }

  remoteNotification() {
    Dialog.showProgressDialog();
    apiUpload.testNotification().then(res => {
      Dialog.dismissLoading();
      toastShort("Success");
    }).catch(err => {
      Dialog.dismissLoading();
      toastShort(err);
    })
  }

  updateToken() {
    if (getUserId() > 0) {
      Dialog.showProgressDialog();
      utils.registerFirebaseToken("", res => {
        Dialog.dismissLoading();
        toastShort(res ? "Upload success" : "Upload failed")
        if (res) {
          this.getUserToken();
        }
      })
    } else {
      toastShort("Please login first");
    }
  }

  copyToken() {
    if (this.state.notifyToken) {
      Clipboard.setString(this.state.notifyToken);
      toastShort('Copied')
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Device Token：{this.state.notifyToken || "none"}</Text>
        <Text style={styles.text}>Server Token：{this.state.serverToken || "none"}</Text>
        { utils.isNotEmpty(this.state.notifyToken) &&
          <View style={styles.text}>
            <Button
              text='Copy Token'
              elevation={2}
              onClick={() => this.copyToken()}
              />
          </View>
        }
        <View style={styles.text}>
          <Button
            text='Send Local Notification'
            elevation={2}
            onClick={() => this.localNotification()}
            />
        </View>
        <View style={styles.text}>
          <Button
            text='Request Remote Notification'
            elevation={2}
            onClick={() => this.remoteNotification()}
            />
        </View>
        { utils.isNotEmpty(this.state.notifyToken) &&
          <View style={styles.text}>
            <Button
              text='Update Firebase Token'
              elevation={2}
              onClick={() => this.updateToken()}
            />
          </View>
        }
        <View style={[ui.flex1, ui.flexcc]}>
          <Text style={styles.os}>{Platform.OS}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...$padding(8,16)
  },
  text: {
    paddingBottom: 12
  },
  os: {
    color: '#999'
  }
})