from plesk_mail_migrator.core.entities.imap_flags import IMAPFlags


class IMAPFlagsUtils(object):
    @staticmethod
    def flags_to_string(flags):
        """Convert flags object to IMAP string

        :type flags: plesk_mail_migrator.core.entities.imap_flags.IMAPFlags
        :rtype: str
        """
        flag_str_parts = []
        for flag in IMAPFlags.all_flags:
            if flags.is_set(flag):
                flag_str_parts.append(flag.imap_string)

        return " ".join(flag_str_parts)

    @staticmethod
    def flags_from_string(flags_str):
        """Create flags object from IMAP string

        :type flags_str: str
        :rtype: plesk_mail_migrator.core.entities.imap_flags.IMAPFlags
        """
        flags = IMAPFlags()

        if flags_str is None:
            return flags

        flags_str = flags_str.lower()

        for flag in IMAPFlags.all_flags:
            if flag.imap_string.lower() in flags_str:
                flags.add_flag(flag)

        return flags

    @staticmethod
    def flags_to_number(flags):
        """Convert flags object to number in mail migrator dump format

        :type flags: plesk_mail_migrator.core.entities.imap_flags.IMAPFlags
        :rtype: str
        """
        flags_number = 0
        for flag in IMAPFlags.all_flags:
            if flags.is_set(flag):
                flags_number |= flag.enum_number

        return flags_number

    @staticmethod
    def flags_from_number(flags_number):
        """Create flags object from number in mail migrator dump format

        :type flags_number: int
        :rtype: plesk_mail_migrator.core.entities.imap_flags.IMAPFlags
        """
        flags = IMAPFlags()
        for flag in IMAPFlags.all_flags:
            if flags_number & flag.enum_number:
                flags.add_flag(flag)
        return flags

    @staticmethod
    def flags_to_maildir_string(flags):
        """Convert flags object to string that could be used in message filename for Maildir

        :type flags: plesk_mail_migrator.core.entities.imap_flags.IMAPFlags
        :rtype: str
        """
        flags_str_parts = []
        for flag in IMAPFlags.all_flags:
            if flags.is_set(flag):
                if flag.maildir_string is not None:
                    flags_str_parts.append(flag.maildir_string)

        flags_str_parts.sort()

        if len(flags_str_parts) > 0:
            return ":2,%s" % ("".join(flags_str_parts))
        else:
            return ""
