"""This module holds the qrcode classes of the ``qrcodes`` app."""

import json
import qrcode


class QRCode:
    """Class to represent a QRCode.

    Attributes
    ----------
    content_type: str
        The QRCode content type.
    context_data: dict
        The dictionary containing data to store in the generated QRCode.

    """

    content_type = "image/png"

    def __init__(self, context_data):
        self.context_data = context_data or {}

    def _get_qrcode_context_data(self, **kwargs):
        """Get the qrcode context data.

        Notes
        -----
        This method is inspired of `get_context_data` in views.
        We can add additional data with kwargs parameter.

        Returns
        -------
        dict
            The wanted context data.

        """

        self.context_data.update(kwargs)
        return self.context_data

    def generate(self):
        """Generate the QRCode.

        Returns
        -------
        Image
            The QRCode containing the wanted data.

        """

        qr_code = qrcode.QRCode(
            version=None,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr_code_data = self._get_qrcode_context_data()
        qr_code.add_data(json.dumps(qr_code_data))
        qr_code.make(fit=True)

        return qr_code.make_image()


class ObjectQRCode(QRCode):
    """A QRCode from an object like a model instance.

    Notes
    -----
    This class must be used when we want create a custom QRCode from an object.
    Just override the `_get_qrcode_context_data` method to pass the needed data.

    Examples
    --------
    We can create a ``ActivityQRCode`` which inherit of ``ObjectQRCode`` to have a specific QRCode.
    This specific QRCode will be initialize with an ``Activity`` instance.

    Attributes
    ----------
    object: object
        The object used to generate the QRCode.

    """

    def __init__(self, obj, context_data=None):
        super().__init__(context_data=context_data)
        self.object = obj

    def get_object(self):
        """Get the instance object to export in QRCode.

        Returns
        -------
        Object
            The wanted object.

        """

        return self.object
