package com.supvan.supvandemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
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.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.supvan.supvanlibrary.PrintingControlInfo.DrawObject;
import com.supvan.supvanlibrary.PrintingControlInfo.PrintPage;
import com.supvan.supvanlibrary.PrintingControlInfo.PrintParameter;
import com.supvan.supvanlibrary.directprinttools.BluetoothManager;
import com.supvan.supvanlibrary.directprinttools.Callback;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView mBluetoothListView;
    private TextView mConnectDevice;
    private Button mPrintButton, mDisconnectButton, mStatusButton, mPrintParameterButton;
    private List<String> mBluetoothData = new ArrayList<>();
    private List<BluetoothDevice> mBluetoothDeviceData = new ArrayList<>();
    private ArrayAdapter<String> mAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBtAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initReceiver();
        addPermissions();
    }

    private void initView(){
        mBluetoothListView = findViewById(R.id.list_view);
        mConnectDevice = findViewById(R.id.connect_device);
        mPrintButton = findViewById(R.id.print_button);
        mStatusButton = findViewById(R.id.print_status_button);
        mDisconnectButton = findViewById(R.id.disconnect_button);
        mPrintParameterButton = findViewById(R.id.print_parameter_button);

        mPrintButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                printImage();
            }
        });

        mPrintParameterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                printParameterImage();
            }
        });

        mStatusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "状态----------" + mBluetoothManager.getStatus(), Toast.LENGTH_LONG).show();
            }
        });

        mDisconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBluetoothManager.closePrinter();
            }
        });
    }

    private void printImage(){
        List<PrintPage> printPages = new ArrayList<>();
        ArrayList<Bitmap> printImages = new ArrayList<>();
        printImages.add(getNewBitmap());
        printImages.add(getNewBitmap());
        printImages.add(getNewBitmap());

        PrintPage printPage1 = new PrintPage(40, 30, 1, null);
        PrintPage printPage2 = new PrintPage(40, 30, 1, null);
        PrintPage printPage3 = new PrintPage(40, 30, 1, null);
        printPages.add(printPage1);
        printPages.add(printPage2);
        printPages.add(printPage3);
        PrintParameter printParameter = new PrintParameter(40,30,1, 0,
                4, 0, 0, 1, 6, true, 0, printPages);
        mBluetoothManager.doPrintImage(printImages, printParameter);
    }

    private void printParameterImage(){
        List<PrintPage> printPages = new ArrayList<>();
        List<DrawObject> drawObjects = new ArrayList<>();
        DrawObject drawObject1 = new DrawObject(false, 6, 5, 10, 2, "线缆sgsdgsdgsdgdsfgsdgdgfsgsdgdsfgsdfgsdgsdfgbxcbs编号", "黑体", 0, 3, false, "TEXT", null);
        DrawObject drawObject2 = new DrawObject(false, 1, 10, 23, 3, "123456", "黑体", 0, 0, false, "CODE_128", null);
        DrawObject drawObject3 = new DrawObject(false, 4, 15, 6, 6, "654321", "黑体", 0, 0, false, "QR_CODE", null);
        DrawObject drawObject4 = new DrawObject(false, 3, 20, 7, 5, "", "", 0, 0, false, "IMAGE", drawableToBitmap(getResources().getDrawable(R.mipmap.tou)));
        drawObjects.add(drawObject1);
        drawObjects.add(drawObject2);
        drawObjects.add(drawObject3);
        drawObjects.add(drawObject4);
        PrintPage printPage = new PrintPage(40, 30, 1, drawObjects);
        printPages.add(printPage);
        PrintParameter printParameter = new PrintParameter(40,30,1, 0,
                4, 0, 0, 1, 6, true, 0, printPages);
        mBluetoothManager.doPrintParameter(printParameter);
    }

    private void initData(){
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothManager = new BluetoothManager(this);
        mBluetoothManager.setCallback(new Callback() {
            @Override
            public void openPrinterResult(boolean result) {
                handleConnect();
            }

            @Override
            public void closePrinterResult(boolean result) {
                mBluetoothData.clear();
                mBluetoothDeviceData.clear();
                mBluetoothListView.setVisibility(View.VISIBLE);
                mConnectDevice.setVisibility(View.GONE);
                startSearch();
            }

            @Override
            public void getStatusResult(int status) {
                Log.e("status", "--------------" + status);
            }

            @Override
            public void doPrintImagesResult(boolean result) {

            }

            @Override
            public void doPrintTextsResult(boolean result) {

            }
        });

        mBluetoothData.clear();
        mBluetoothDeviceData.clear();

        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,mBluetoothData);

        mBluetoothListView.setAdapter(mAdapter);
        mBluetoothListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mBluetoothManager.openPrinter(mBluetoothDeviceData.get(position));
            }
        });
    }

    public void startSearch() {
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }
        mBtAdapter.startDiscovery();
    }

    private void addPermissions(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 321);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    //如果没有获取权限，那么可以提示用户去设置界面--->应用权限开启权限
                } else {
                    startSearch();
                }
            }
        }
    }

    private void handleConnect(){
        mBluetoothListView.setVisibility(View.GONE);
        mConnectDevice.setVisibility(View.VISIBLE);
    }

    private Bitmap getNewBitmap() {
        int width = 20 * 8;
        int height = 5 * 8;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(4);
        paint.setStyle(Paint.Style.STROKE);
        RectF rectF = new RectF(0, 0, width, height);
        String text = "SUPVAN";
        canvas.drawRect(rectF, paint);

        float fontSize = 20f;
        for (float i = 100f; i > 0f; i--) {
            paint.setTextSize(i);
            float textWidth = paint.measureText(text);
            if (textWidth < width - 10) {
                fontSize = i;
                break;
            }
        }

        Rect bounds = new Rect();

        for (float i = fontSize; i > 0f; i--) {
            paint.setTextSize(i);
            paint.getTextBounds(text, 0, text.length(), bounds);
            if (bounds.height() < height - 20){
                fontSize = i;
                break;
            }
        }

        paint.setStyle(Paint.Style.FILL);

        Paint.FontMetrics fontMetrics= paint.getFontMetrics();
        float distance=(fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
        float baseline = rectF.centerY() + distance;
        canvas.drawText(text, (width - paint.measureText(text)) / 2, baseline, paint);
        return bitmap;
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        //声明将要创建的bitmap
        Bitmap bitmap = null;
        //获取图片宽度
        int width = drawable.getIntrinsicWidth();
        //获取图片高度
        int height = drawable.getIntrinsicHeight();
        //图片位深，PixelFormat.OPAQUE代表没有透明度，RGB_565就是没有透明度的位深，否则就用ARGB_8888。详细见下面图片编码知识。
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        //创建一个空的Bitmap
        bitmap = Bitmap.createBitmap(width,height,config);
        //在bitmap上创建一个画布
        Canvas canvas = new Canvas(bitmap);
        //设置画布的范围
        drawable.setBounds(0, 0, width, height);
        //将drawable绘制在canvas上
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        mBluetoothManager.onDestroy();
    }

    private void initReceiver() {
        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intent.addAction(BluetoothDevice.ACTION_FOUND);//搜索发现设备
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索发现设备
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//检测蓝牙连接状态
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//检测设备配对状态
        registerReceiver(mReceiver, intent);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                if (TextUtils.isEmpty(name)){
                    return;
                }
                Log.e("mainActivity",name);
                if (!mBluetoothDeviceData.contains(device)){
                    mBluetoothDeviceData.add(device);
                    mBluetoothData.add(name);
                    mAdapter.notifyDataSetChanged();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {}
        }
    };
}