package com.jcf.sportpager;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by jon on 11/07/2016.
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
    private final static String TAG = "MyFirebaseMsgService";
    private final static int REQUEST_CODE = 123;
    private final static int ID_NOTIFICATION = 123;
    //private String rowId;
    //private String firebase_id;
    //public String messageBody;
    //public String messageTitle;


    @Override
    public void onDeletedMessages()
    {
        super.onDeletedMessages();
        Log.d(TAG, "MyFirebaseMessagingService: onDeletedMessages");
    }

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO(developer): Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        //String messageBody = remoteMessage.getNotification().getBody();
        //String messageTitle = remoteMessage.getNotification().getTitle();
        Map messagedata = remoteMessage.getData();
        String rowId = (String)messagedata.get("rowId");
        String firebase_id = (String)messagedata.get("firebase_id");
        String messageBody = (String)messagedata.get("body");
        String messageTitle = (String)messagedata.get("title");
        Log.d(TAG, "Notification Message data.rowId: " + rowId);
        Log.d(TAG, "Notification Message data.firebase_id: " + firebase_id);

        Log.d(TAG, "Notification Message Body: " + messageBody);
        Log.d(TAG, "Notification Message Title: " + messageTitle);
        Aplicacion.actualizarTipoPorId(rowId, "recibido", messageTitle);

        sendNotification(messageBody, messageTitle);
        //sendOKalServidor(rowId, firebase_id);
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */

    private void sendNotification(String messageBody, String messageTitle)
    {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notificacion_sp)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                        R.drawable.notificacion_sp))
                //        R.drawable.firebase_lockup_400))
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                //.setSubText("tercera línea")
                .setTicker("Sport Pager")
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(ID_NOTIFICATION, notificationBuilder.build());
        //sendOKalServidor(rowId, firebase_id);
    }

    private void sendOKalServidor(String mrowId, String mfirebase_id){
        JSONObject jsonParam = new JSONObject();

        try
        {
            jsonParam.put("rowId", mrowId);
            jsonParam.put("firebase_id", mfirebase_id);
            String mensaje = jsonParam.toString();
            RestPostInner rp = new RestPostInner();
            String ruta = Aplicacion.URL_SERVER + "/sportpager/ack_firebase";
            rp.execute(ruta, mensaje);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

    }



    public class RestPostInner extends AsyncTask<String, String, String>
    {
        private static final String TAG = "MyFirebaseMsgService";

        public RestPostInner()
        {
            super();
            // setear las variables de contexto, si es necesario
        }

        @Override
        protected String doInBackground(String... params)
        {
            DataOutputStream printout;
            String ruta = params[0];
            //String query = params[1];

            try
            {
                String urlString = ruta;
                URL url = new URL(urlString);
            /*
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("tokenId", query);
            String message =jsonParam.toString();
            */
                String message =params[1];
                Log.i(TAG, "Antes de url.openConnection()");
                HttpURLConnection conn  = (HttpURLConnection) url.openConnection();
                Log.i(TAG, "Después de url.openConnection()");
                conn.setReadTimeout( 10000 /*milliseconds*/ );
                conn.setConnectTimeout( 15000 /* milliseconds */ );
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setFixedLengthStreamingMode(message.getBytes().length);

                //make some HTTP header nicety
                conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                //open
                conn.connect();

                //setup send
                OutputStream os = new BufferedOutputStream(conn.getOutputStream());
                os.write(message.getBytes());
                //clean up
                os.flush();


                //JSONObject jsonObject = new JSONObject();
                InputStream inputStream;
                // get stream
                if (conn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = conn.getInputStream();
                } else {
                    inputStream = conn.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }

                return response;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onCancelled()
        {
            super.onCancelled();
        }

        @Override
        protected void onCancelled(String s)
        {
            super.onCancelled(s);
        }

        @Override
        protected void onPostExecute(String s)
        {
            super.onPostExecute(s);
            //notificar();
            Log.i(TAG, "onPostExecute: " + s);
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(String... values)
        {
            super.onProgressUpdate(values);
        }

        /*
        protected void notificar(){
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), REQUEST_CODE, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.notificacion_sp)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                            R.drawable.notificacion_sp))
                    //        R.drawable.firebase_lockup_400))
                    .setContentTitle(messageTitle)
                    .setContentText(messageBody)
                    //.setSubText("tercera línea")
                    .setTicker("Sport Pager")
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(ID_NOTIFICATION, notificationBuilder.build());
        }
        */
    }

    public class JavaScriptInner extends AsyncTask<String, String, String>
    {
        private static final String TAG = "MyFirebaseMsgService";

        public JavaScriptInner()
        {
            super();
            // setear las variables de contexto, si es necesario
        }

        @Override
        protected String doInBackground(String... params)
        {
            String ruta = params[0];
            publishProgress(ruta);
            return null;
        }

        @Override
        protected void onCancelled()
        {
            super.onCancelled();
        }

        @Override
        protected void onCancelled(String s)
        {
            super.onCancelled(s);
        }

        @Override
        protected void onPostExecute(String s)
        {
            super.onPostExecute(s);
            //notificar();
            Log.i(TAG, "onPostExecute: " + s);
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(String... values)
        {
            super.onProgressUpdate(values);

            Aplicacion.Navegador("javascript:inicializarRecibidos()");
        }

    }

}
