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",
    		  "click_action": "fcm.ACTION.HELLO"
        }
    	},
    	"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;
