import FirebaseConstants from "./FirebaseConstants";
import { Platform, Alert } from "react-native";

const API_URL = "https://fcm.googleapis.com/fcm/send";

class FirebaseClient {

  constructor() {
    this.sendData = this.sendData.bind(this);
    this.sendNotification = this.sendNotification.bind(this);
    this.sendNotificationWithData = this.sendNotificationWithData.bind(this);
  }

  sendNotification(token) {
    let body = {
    	"to": token,
      "notification":{
    		"title": "Simple FCM Client",
    		"body": "This is a notification with only NOTIFICATION.",
    		"sound": "default"
    	},
    	"priority": 10
    }

    if(Platform.OS === 'android'){
      body = {
        "to": token,
      "data":{
        "custom_notification": {
    		  "title": "Simple FCM Client",
    		  "body": "This is a notification with only NOTIFICATION.",
    		  "sound": "default",
		"priority": "high"
        }
    	},
    	"priority": 10
      }
    }

    this._send(JSON.stringify(body), "notification");
  }

  sendData(token) {
    let body = {
    	"to": token,
      "data":{
    		"title": "Simple FCM Client",
    		"body": "This is a notification with only DATA.",
    		"sound": "default"
    	},
    	"priority": "normal"
    }

    this._send(JSON.stringify(body), "data");
  }

  sendNotificationWithData(token) {
    let body = {
      "to": token,
      "notification":{
    		"title": "Simple FCM Client",
    		"body": "This is a notification with NOTIFICATION and DATA (NOTIF).",
				"sound": "default"
    	},
    	"data":{
    		"hello": "there"
    	},
    	"priority": "high"
    }

    this._send(JSON.stringify(body), "notification-data");
  }

  async _send(body, type) {
		if(FirebaseClient.KEY === 'YOUR_API_KEY'){
			Alert.alert('Set your API_KEY in app/FirebaseConstants.js')
			return;
		}
  	let headers = new Headers({
  		"Content-Type": "application/json",
      "Authorization": "key=" + FirebaseConstants.KEY
  	});

		try {
			let response = await fetch(API_URL, { method: "POST", headers, body });
			response = await response.json();
			if(!response.success){
				Alert.alert('Failed to send notification, check error log')
			}
			console.log(response);
		} catch (err) {
			Alert.alert(err && err.message)
		}
  }

}

let firebaseClient = new FirebaseClient();
export default firebaseClient;

@@ -2038,16 +2038,51 @@
 ody %7D);%0A
+%09%09%09console.log(response);%0A%09%09%09try%7B%0A%09
 %09%09%09respo
@@ -2113,16 +2113,17 @@
 n();%0A%09%09%09
+%09
 if(!resp
@@ -2137,16 +2137,105 @@
 ccess)%7B%0A
+%09%09%09%09%09Alert.alert('Failed to send notification, check error log')%0A%09%09%09%09%7D%0A%09%09%09%7D catch (err)%7B%0A
 %09%09%09%09Aler
@@ -2294,39 +2294,13 @@
 g')%0A
+
 %09%09%09%7D%0A
-%09%09%09console.log(response);%0A
 %09%09%7D 

fix error log