package com.unitech.utility.btscanner;


import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import org.tinylog.Logger;

import java.util.EnumMap;
import java.util.Map;

import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;

public class BtImageFragment extends Fragment {
    private Context context;
    public BtImageFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bt_mac, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.invalidate();
        TextView btMacAddress = view.findViewById(R.id.txt_bt_img);
        ImageView btCode93 = view.findViewById(R.id.img_bt_mac);
        //---------------------------------- barcode image -----------------------------------------
        final SharedPreferences sharedPreferences = context.getSharedPreferences(getString(R.string.LocalInfo), Context.MODE_PRIVATE);
        String PairingBarcodeContentTemp = sharedPreferences.getString("PairingBarcodeContent", "");
        Logger.debug("PairingBarcodeContentTemp = "+PairingBarcodeContentTemp);
        btMacAddress.setText(PairingBarcodeContentTemp);
        if (PairingBarcodeContentTemp != null) {
            try {
                Bitmap Code93BitmapOfAndroidBtMacAddress = encodeAsBitmap(PairingBarcodeContentTemp.replace(":", "").toUpperCase(), BarcodeFormat.CODE_93, 150, 150);
                int width = getResources().getDisplayMetrics().widthPixels;
                int height = (width * Code93BitmapOfAndroidBtMacAddress.getHeight()) / Code93BitmapOfAndroidBtMacAddress.getWidth();
                Code93BitmapOfAndroidBtMacAddress = Bitmap.createScaledBitmap(Code93BitmapOfAndroidBtMacAddress, width, height, true);
                btCode93.setImageBitmap(Code93BitmapOfAndroidBtMacAddress);
            } catch (WriterException e) {
                e.printStackTrace();
            }
        }
        //------------------------------------------------------------------------------------------
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    static Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
        if (contents == null) {
            return null;
        }
        Map <EncodeHintType, Object> hints = null;
        String encoding = guessAppropriateEncoding(contents);
        if (encoding != null) {
            hints = new EnumMap <>(EncodeHintType.class);
            hints.put(EncodeHintType.CHARACTER_SET, encoding);
        }
        BitMatrix result;
        try {
            result = new MultiFormatWriter().encode(contents, format, img_width, img_height, hints);
        } catch (IllegalArgumentException iae) {
            // Unsupported format
            return null;
        }
        int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    private static String guessAppropriateEncoding(CharSequence contents) {
        // Very crude at the moment
        for (int i = 0; i < contents.length(); i++) {
            if (contents.charAt(i) > 0xFF) {
                return "UTF-8";
            }
        }
        return null;
    }

}

