package com.helldivers.app;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.util.HashMap;
import java.util.Map;

public class ActivityQR extends AppCompatActivity {

    private static final String INSTAGRAM_URL = "https://www.instagram.com/la_forja_gigante";
    private static final int QR_SIZE = 512;

    private SoundManager soundManager;
    private ImageView qrImageView;
    private ImageButton btnVolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr);

        soundManager = new SoundManager(this);

        qrImageView = findViewById(R.id.qr_image);
        btnVolver = findViewById(R.id.btn_volver);

        generateAndDisplayQR();

        if (btnVolver != null) {
            btnVolver.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    private void generateAndDisplayQR() {
        try {
            QRCodeWriter writer = new QRCodeWriter();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            BitMatrix bitMatrix = writer.encode(INSTAGRAM_URL, BarcodeFormat.QR_CODE, QR_SIZE, QR_SIZE, hints);

            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

            int qrColor = 0xFFFFFFFF; // Blanco para los módulos del QR
            int transparent = 0x00000000; // Transparente para el fondo

            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    bmp.setPixel(x, y, bitMatrix.get(x, y) ? qrColor : transparent);
                }
            }

            if (qrImageView != null) {
                qrImageView.setImageBitmap(bmp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundManager != null) {
            soundManager.release();
        }
        if (qrImageView != null) {
            qrImageView.setImageBitmap(null);
        }
    }
}