package com.aplusinformatique.aplusmanager.Services;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.aplusinformatique.aplusmanager.R;

import device.common.DecodeResult;
import device.common.ScanConst;
import device.sdk.ScanManager;

public class GererScannerPM80 extends Service {

    private static final String TAG = "distrimobilelog_PM80";
    private static final String actionReply = "com.aplusinformatique.aplusmanager.scannerreponse";
    private static ScanManager mScanner;
    private static DecodeResult mDecodeResult;
    private final Context mContext = this;
    private final String actionActivation = "com.aplusinformatique.aplusmanager.scanneractivation";
    private final String actionErreurInitialisation = "com.aplusinformatique.aplusmanager.erreurinitscanner";

    //Gestion du Heart Beat (généré par Distrimobile)
    private final String actionAccuseHeartBeat = "com.aplusinformatique.aplusmanager.accuseheartbeat";
    private final String actionPointMobile = "device.common.USERMSG";
    //Broadcast receiver Fin Service
    private final String actionFinService = "com.aplusinformatique.aplusmanager.finservicepm80";
    private final int ID_NOTIFICATION = 1005;
    Handler h = new Handler();
    Runnable r;
    private int accuseHeartBeat = 0;
    private boolean DeclencherFinService = false;
    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(actionPointMobile)) {
                if (mScanner != null) {
                    try {
                        DecodeResult mDecodeResult = new DecodeResult();
                        mScanner.aDecodeGetResult(mDecodeResult);
                        String sRes = String.valueOf(mDecodeResult.toString());
                        if (!sRes.equals("READ_FAIL")) {
                            Log.d(TAG, "lecture CAB PM80 : " + sRes);
                            renvoyerValeur(context, sRes);
                        }
                    } catch (Exception eee) {

                    }
                }
            }

            if (action.equals(actionActivation)) {
                int valeur = Integer.valueOf(intent.getExtras().getString("valeur", "0"));
                ActivationScanner(valeur);
            }

            if (action.equals(actionAccuseHeartBeat)) {
                accuseHeartBeat = 0;
            }

            if (action.equals(actionFinService)) {
                FinService();
            }
        }
    };

    public static void renvoyerValeur(Context context, String s) {
        Intent replyIntent = new Intent();
        replyIntent.setAction(actionReply);
        replyIntent.putExtra("data", s);
        context.sendBroadcast(replyIntent);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        Log.d("distrimobile", "Gerer Scanner PM80");

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.taskbar_icon_cb)
                .setContentTitle("Scanner PM80")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_NOTIFICATION, notification);

        mScanner = new ScanManager();
        mDecodeResult = new DecodeResult();
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {

        }
        initScanner();

        //Si l'application Distrimobile ne réponds pas aux intent, on tue le service
        //Contrôle toutes les 5 secondes
        h.postDelayed(r = new Runnable() {
            public void run() {

                accuseHeartBeat += 1;
                Log.d(TAG, "compteur accusé heartbeat : " + String.valueOf(accuseHeartBeat));
                if (accuseHeartBeat > 4) {
                    Log.d(TAG, "accusés sans réponses");
                    DeclencherFinService = true;
                }

                if (DeclencherFinService) {
                    FinService();
                } else {
                    h.postDelayed(this, 5 * 1000);
                }
            }
        }, 5 * 1000);

        // Create a filter for the broadcast intent
        IntentFilter filter = new IntentFilter();
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        filter.addAction(actionPointMobile);
        filter.addAction(actionActivation);
        filter.addAction(actionAccuseHeartBeat);
        filter.addAction(actionFinService);
        registerReceiver(myBroadcastReceiver, filter);

        return START_STICKY;
    }

    private void initScanner() {
        if (mScanner != null) {
            mScanner.aDecodeSetResultType(ScanConst.ResultType.DCD_RESULT_USERMSG);
            mScanner.aDecodeSetTriggerMode(ScanConst.TriggerMode.DCD_TRIGGER_MODE_ONESHOT);
            mScanner.aDecodeSetTerminator(ScanConst.Terminator.DCD_TERMINATOR_NONE);
            ActivationScanner(1);
        } else {
            Log.d(TAG, "Erreur initialisation GererScannerPM80");
            Intent replyIntent = new Intent();
            replyIntent.setAction(actionErreurInitialisation);
            mContext.sendBroadcast(replyIntent);
            FinService();
        }
    }

    private void ActivationScanner(int valeur) {
        if (mScanner != null) {
            if (valeur == 1) {
                mScanner.aDecodeSetVibratorEnable(1);
                mScanner.aDecodeSetBeepEnable(1);
                mScanner.aDecodeSetDecodeEnable(1);
            } else {
                mScanner.aDecodeSetDecodeEnable(0);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("distrimobile", "onDestroy GererScannerPM80");

        if (mScanner != null) {
            mScanner.aDecodeSetDecodeEnable(0);
            mScanner = null;
        }

        if (h != null) {
            h.removeCallbacks(r);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager) {
        String channelId = TAG;
        String channelName = "Scanner PM80";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_LOW);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }

    private void FinService() {
        stopForeground(true);
        stopSelf();
    }
}
