package com.example.quiz.utils;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.widget.Toast;

import androidx.annotation.RequiresPermission;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.anggastudio.printama.Printama;
import com.anggastudio.printama.PrintamaUI;


public class BluetoothUtils {
    public static final int PERMISSION_REQUEST_BLUETOOTH_CONNECT = 432;


    public static boolean needsBluetoothPermissions() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.S;
    }

    public static boolean hasBluetoothPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT)
                    == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN)
                            == PackageManager.PERMISSION_GRANTED;
        } else {
            return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED;
        }
    }

    public static void requestBluetoothPermission(FragmentActivity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{
                            Manifest.permission.BLUETOOTH_SCAN,
                            Manifest.permission.BLUETOOTH_CONNECT
                    },
                    PERMISSION_REQUEST_BLUETOOTH_CONNECT);
        } else {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_REQUEST_BLUETOOTH_CONNECT);
        }
    }

    /** Fournit l’intent pour activer Bluetooth */
    public static Intent getEnableBluetoothIntent() {
        return new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    }

    /** Affiche la liste des imprimantes */
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    public static void showPrinterList(Context context, FragmentActivity activity) {
        PrintamaUI.showPrinterList(activity, selectedDevice -> {
            if (selectedDevice != null) {
                String name = Printama.getSavedPrinterName(context);
                showToast("Connected to " + name, context);
            } else {
                showToast("Failed to choose printer", context);
            }
        });
    }

    private static void showToast(String msg, Context c) {
        Toast.makeText(c, msg, Toast.LENGTH_SHORT).show();
    }
}
