package com.xixun.launcher;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.view.Choreographer;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.activity.ComponentActivity;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;

public class MainActivity extends ComponentActivity implements Choreographer.FrameCallback {

    @RequiresApi(api = Build.VERSION_CODES.S)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        var msg = "==== MainActivity onCreate ==== UI Thread: " + Thread.currentThread().getId();
        Util.println(msg);

        Button btnProg = findViewById(R.id.btnProg);
        btnProg.setOnClickListener((View v)->startActivity(new Intent(MainActivity.this, ProgActivity.class)));

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());

//        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            if(! Environment.isExternalStorageManager()) {// android 11  且 不是已经被拒绝
//                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
//                intent.setData(Uri.parse("package:" + getPackageName()));
//                startActivityForResult(intent, 1024);
//            }
//        } else {
            if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED)
                init();
            else {
                Util.println("---- No permission, Try again ...");
                ActivityCompat.requestPermissions(this, new String[] {
                        android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        android.Manifest.permission.BLUETOOTH,
                        android.Manifest.permission.BLUETOOTH_ADMIN,
                        android.Manifest.permission.BLUETOOTH_CONNECT,
                        android.Manifest.permission.BLUETOOTH_SCAN,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                        android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
                        android.Manifest.permission.INTERNET
                }, 999);
            }
//        }
        var intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
        intentFilter.addDataScheme("file");
        registerReceiver(new BroadcastReceiver(){
            long lastMs;
            @Override
            public void onReceive(Context context, Intent intent) {
                var path = intent.getData().getPath();
                Util.println("\nMEDIA_MOUNTED path: "+path);
                var ms = System.currentTimeMillis();
                if(ms-lastMs<1000) return;
                lastMs = ms;
                Util.makeText(MainActivity.this, "MEDIA_MOUNTED path: "+path).show();
            }
        }, intentFilter);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return;
        Util.println("onActivityResult "+resultCode+" isExternalStorageManager "+Environment.isExternalStorageManager());
        if (requestCode == 1024) {
            if(Environment.isExternalStorageManager()) init();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Util.println("onRequestPermissionsResult "+grantResults[0]);
        Util.makeText(MainActivity.this, "onRequestPermissionsResult "+grantResults[0]).show();
        if (requestCode == 999 && grantResults[0] == PackageManager.PERMISSION_GRANTED && Util.backImgFile == null)
            init();
    }

    ArrayList<BroadcastReceiver> reces = new ArrayList<>();
    BluetoothDevice mBluetoothDevice;
//    BluetoothAdapter bluetoothAdapter;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public void init() {
        var dir = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ? Environment.getExternalStorageDirectory().getAbsolutePath() + "/Launcher" : getExternalFilesDir(null).getAbsolutePath();
        var msg = "---- dir " + dir;
        Util.println(msg);
        Util.programsDir = dir + "/programs";
        Util.backImgFile = dir + "/background";

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //filter.addAction(BluetoothDevice.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        BroadcastReceiver rece;
        registerReceiver(rece = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                var action = intent.getAction();
                Util.println("\nBluetooth action: " + action);
                Util.makeText(MainActivity.this, "Bluetooth action: " + action).show();
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    mBluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        Util.println("No Permission BLUETOOTH_CONNECT");
                        Util.makeText(MainActivity.this, "No Permission BLUETOOTH_CONNECT").show();
                        return;
                    }
                    Util.println("Device Name: " + mBluetoothDevice.getName() + " Address: " + mBluetoothDevice.getAddress() + " BondState: " + mBluetoothDevice.getBondState());
                    if (mBluetoothDevice.getName() == null || !mBluetoothDevice.getName().equals("RCSP"))
                        return;
                    if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                        try {
                            mBluetoothDevice.createBond();
                        } catch (Exception e) {
                            Util.printStackTrace(e);
                        }
                    }
//                } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
//                    int status = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
//                    if (BluetoothAdapter.STATE_ON == status) {
//                        mBluetoothAdapter.startDiscovery();
//                        Log.d(TAG, "mBluetoothAdapter.startDiscovery---STATE_ON");
//                    }
//                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//                    if (!isConnected) {
//                        mBluetoothAdapter.startDiscovery();
//                        Log.d(TAG, "mBluetoothAdapter.startDiscovery---ACTION_DISCOVERY_FINISHED");
//                    }
//                } else if (BluetoothInputDevice.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
//                    int newState = intent.getExtras().getInt(BluetoothProfile.EXTRA_STATE);
//                    switch (newState) {
//                        case BluetoothProfile.STATE_CONNECTING:
//                            Log.d(TAG, "CONNECTING");
//                            Toast.makeText(context, R.string.bluetooth_connecting, Toast.LENGTH_SHORT).show();
//                            break;
//                        case BluetoothProfile.STATE_CONNECTED:
//                            Log.d(TAG, "CONNECTED");
//                            Toast.makeText(context, R.string.bluetooth_connected, Toast.LENGTH_SHORT).show();
//                            RcConnectActivity.this.finish();
//                            break;
//                    }
                }
            }
        }, filter);
        reces.add(rece);

//        var intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
//        intentFilter.addDataScheme("file");
//        registerReceiver(new BroadcastReceiver() {
//            long lastMs;
//
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                var path = intent.getData().getPath();
//                Util.println("\nMEDIA_MOUNTED path: " + path);
//                var ms = System.currentTimeMillis();
//                if (ms - lastMs < 1000) return;
//                lastMs = ms;
//                Util.makeText(MainActivity.this, "MEDIA_MOUNTED path: " + path).show();
//            }
//        }, intentFilter);

//        try {
//            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//            if (bluetoothAdapter == null) {
//                Util.println("BluetoothAdapter is Null");
//                Util.makeText(MainActivity.this, "BluetoothAdapter is Null").show();
//            } else {
//                Util.println("BluetoothState: " + bluetoothAdapter.getState());
//                if (bluetoothAdapter.isEnabled()) {
//                    Util.println("startDiscovery");
//                    Util.makeText(MainActivity.this, "bluetoothAdapter startDiscovery").show();
//                    bluetoothAdapter.startDiscovery();
//                } else {
//                    Util.println("enable");
//                    Util.makeText(MainActivity.this, "bluetoothAdapter enable").show();
//                    bluetoothAdapter.enable();
//                }
//            }
//        } catch (Exception e) {
//            Util.printStackTrace(e);
//            Util.makeText(this, Util.toStr(e)).show();
//        }
        choreographer.postFrameCallback(this);
    }

    Choreographer choreographer = Choreographer.getInstance();
    int frameCnt;

    @Override
    public void doFrame(long frameTimeNanos) {
        choreographer.postFrameCallback(this);
        if(--frameCnt > 0) return;
        frameCnt = 600;
        //System.out.println("root Width: "+root.getWidth());
//        if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
//            Util.println("No Permission BLUETOOTH_SCAN");
//            return;
//        }
//        Util.println("BluetoothAdapter is Discovering: " + bluetoothAdapter.isDiscovering());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for(var rece : reces) unregisterReceiver(rece);
    }
}