import base64
from typing import Union


class B64Helper:

    @staticmethod
    def encode(string: str) -> str:
        """
        Encode a string with base64
        :param string:
        :return:
        """
        return base64.b64encode(string.encode("utf-8")).decode("utf-8")

    @staticmethod
    def decode(string: str) -> str:
        """
        Decode a string with base64
        :param string:
        :return:
        """
        return base64.b64decode(string).decode("utf-8")

    @staticmethod
    def is_b64(sb: Union[str, bytes]) -> bool:
        """
        Check if a string is base64 encoded
        :param Union[str, bytes] sb:
        :return:
        :rtype: bool
        """
        try:
            if isinstance(sb, str):
                # If there's any unicode here, an exception will be thrown and the function will return false
                sb_bytes = bytes(sb, "ascii")
            elif isinstance(sb, bytes):
                sb_bytes = sb
            else:
                raise ValueError("Argument must be string or bytes")
            return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes
        except ValueError:
            return False
