package org.mercury_im.messenger.android.ui.openpgp;

import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;

import org.jivesoftware.smackx.colors.ConsistentColor;
import org.mercury_im.messenger.android.util.ColorUtil;
import org.pgpainless.key.OpenPgpV4Fingerprint;

public class OpenPgpV4FingerprintFormatter {

    /**
     * Split an OpenPGP fingerprint into 10 blocks of length 4.
     *
     * @param fingerprint fingerprint
     * @return blocks
     */
    public static String[] getFingerprintBlocks(OpenPgpV4Fingerprint fingerprint) {
        String[] blocks = new String[10];
        for (int i = 0; i < 10; i++) {
            blocks[i] = fingerprint.subSequence(i*4, (i+1)*4).toString();
        }
        return blocks;
    }

    /**
     * Calculate consistent colors for 10 blocks of length 4 of the fingerprint.
     *
     * @param blocks Array of 10 OpenPGP fingerprint blocks of length 4
     * @param consistentColorSettings settings for color generation
     * @return array of generated colors
     */
    public static int[] getColorsForFingerprintBlocks(String[] blocks,
                                                      ConsistentColor.ConsistentColorSettings consistentColorSettings) {
        int[] colors = new int[10];
        for (int i = 0; i < 10; i++) {
            if (consistentColorSettings != null) {
                colors[i] = ColorUtil.consistentColor(blocks[i], consistentColorSettings);
            } else {
                colors[i] = ColorUtil.consistentColor(blocks[i]);
            }
        }
        return colors;
    }

    public static Spannable formatOpenPgpV4Fingerprint(OpenPgpV4Fingerprint fingerprint) {
        return formatOpenPgpV4Fingerprint(fingerprint, null);
    }

    public static Spannable formatOpenPgpV4Fingerprint(OpenPgpV4Fingerprint fingerprint,
                                                       ConsistentColor.ConsistentColorSettings settings) {
        String[] blocks = getFingerprintBlocks(fingerprint);
        int[] colors = getColorsForFingerprintBlocks(blocks, settings);

        StringBuilder formattedFingerprint = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            formattedFingerprint.append(blocks[i]);
            if (i == 4) {
                formattedFingerprint.append('\n');
                continue;
            }
            if (i != 9) {
                formattedFingerprint.append(' ');
            }
        }

        Spannable spannable = new SpannableString(formattedFingerprint.toString());
        for (int i = 0; i < 10; i++) {
            spannable.setSpan(new ForegroundColorSpan(colors[i]), i*5, (i+1)*5-1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return spannable;
    }
}
