/*
 * @(#)Base64Format.java
 *
 * Copyright (c) 2002-2003 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 */

package com.jscape.util;

import java.util.Arrays;

import static com.jscape.util.Parameters.*;

/**
 * Base64 format.
 *
 * @author Alex
 */
@SuppressObfuscation
public class Base64Format
        implements BinaryDataFormat {

    public static final int DEFAULT_LINE_LENGTH = 72;
    private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();

    private static byte[] codes = new byte[256];

    static {
        Arrays.fill(codes, (byte) -1);

        for (int i = 'A'; i <= 'Z'; ++i) {
            codes[i] = (byte) (i - 'A');
        }

        for (int i = 'a'; i <= 'z'; ++i) {
            codes[i] = (byte) (26 + i - 'a');
        }

        for (int i = '0'; i <= '9'; ++i) {
            codes[i] = (byte) (52 + i - '0');
        }

        codes['+'] = 62;
        codes['/'] = 63;
    }

    private static char[] encode(byte[] data, int lineLength) {
        assertGreater(lineLength, 0, "Bad line length.");

        char[] out = new char[((data.length + 2) / 3) * 6]; // for every 3 chars you could have 6 with CRLF
        int count = 0;
        int index = 0;

        for (int i = 0; i < data.length; i += 3, index += 4) {
            boolean quad = false;
            boolean trip = false;

            int val = (0xFF & data[i]);

            val <<= 8;

            if ((i + 1) < data.length) {
                val |= (0xFF & data[i + 1]);
                trip = true;
            }

            val <<= 8;

            if ((i + 2) < data.length) {
                val |= (0xFF & data[i + 2]);
                quad = true;
            }

            out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 1] = alphabet[val & 0x3F];
            val >>= 6;
            out[index] = alphabet[val & 0x3F];

            // break up lines based on line length

            count += 4;

            if (count == lineLength) {
                // add CRLF
                out[index + 4] = '\r';
                out[index + 5] = '\n';
                index += 2;
                // reset count
                count = 0;
            }

        }

        char[] tmp = new char[index];
        System.arraycopy(out, 0, tmp, 0, index);

        return tmp;
    }

    private static byte[] decode(char[] data) {
        // as our input could contain non-BASE64 data (newlines,
        // whitespace of any sort, whatever) we must first adjust
        // our count of USABLE data so that...
        // (a) we don't misallocate the output array, and
        // (b) think that we miscalculated our data length
        //     just because of extraneous throw-away junk

        int tempLen = data.length;

        for (int ix = 0; ix < data.length; ++ix) {
            if ((data[ix] > 255) || codes[data[ix]] < 0) {
                --tempLen; // ignore non-valid chars and padding
            }

        }

        // calculate required length:
        //  -- 3 bytes for every 4 valid base64 chars
        //  -- plus 2 bytes if there are 3 extra base64 chars,
        //     or plus 1 byte if there are 2 extra.
        int len = (tempLen / 4) * 3;

        if ((tempLen % 4) == 3) {
            len += 2;
        }

        if ((tempLen % 4) == 2) {
            len += 1;
        }

        byte[] out = new byte[len];

        int shift = 0; // # of excess bits stored in accum
        int accum = 0; // excess bits
        int index = 0;

        // we now go through the entire array (NOT using the 'tempLen' value)
        for (int ix = 0; ix < data.length; ++ix) {
            int value = (data[ix] > 255) ? -1 : codes[data[ix]];

            if (value >= 0) { // skip over non-code
                accum <<= 6; // bits shift up by 6 each time thru
                shift += 6; // loop, with new bits being put in
                accum |= value; // at the bottom.
                if (shift >= 8) { // whenever there are 8 or more shifted in,
                    shift -= 8; // writing them out (from the top, leaving any
                    out[index++] = (byte) ((accum >> shift) & 0xff); // excess at the bottom for next iteration.
                }
            }
            // we will also have skipped processing a padding null byte ('=') here;
            // these are used ONLY for padding to an even length and do not legally
            // occur as encoded data. for this reason we can ignore the fact that
            // no index++ operation occurs in that special case: the out[] array is
            // initialized to all-zero bytes to start with and that works to our
            // advantage in this combination.
        } // if there is STILL something wrong we just have to throw up now!
        if (index != out.length) {
            throw new RuntimeException("Miscalculated data length (wrote "
                                               + index
                                               + " instead of "
                                               + out.length
                                               + ")");
        }
        return out;
    }

    public static String formatData(byte[] data, int lineLength) {
        if (data == null) {
            return "";
        }
        
        return new String(encode(data, lineLength));
    }

    public static String formatData(byte[] data) {
        return formatData(data, Integer.MAX_VALUE);
    }

    public static String formatData(byte[] data, int offset, int length, int lineLength) {
        if (data == null) {
            return "";
        }
        
        assertArrayValid(data, offset, length);

        byte[] tmp = new byte[length];
        System.arraycopy(data, offset, tmp, 0, tmp.length);
        return new String(encode(tmp, lineLength));
    }

    public static String formatData(byte[] data, int offset, int length) {
        return formatData(data, offset, length, Integer.MAX_VALUE);
    }

    public static byte[] parseData(String data) {
        assertNotNull(data);
        return decode(data.toCharArray());
    }

    public String format(byte[] data) {
        return formatData(data);
    }

    public String format(byte[] data, int offset, int length, int lineLength) {
        return formatData(data, offset, length, lineLength);
    }

    public byte[] parse(String data) {
        return parseData(data);
    }

}
