/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *  
 */
// https://issues.redhat.com/browse/TEIID-5709
package org.teiid.util;


import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.Streamable;
import org.teiid.core.util.Base64;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.Arrays;
import org.graalvm.shadowed.com.ibm.icu.text.CharsetDetector;
import org.graalvm.shadowed.com.ibm.icu.text.CharsetMatch;

public final class CharsetUtils {
	
	public static final String HEX_NAME = "HEX"; //$NON-NLS-1$
	static final char[] hex_alphabet = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

	public static final Charset HEX = new Charset(HEX_NAME, new String[0]) {
				
		@Override
		public CharsetEncoder newEncoder() {
			return new FixedEncoder(this, 2, .5f, 1) {
	    		char[] chars = new char[2]; 

		    	@Override
		    	protected CoderResult encode(ByteBuffer out) {
		    		this.cb.get(chars);
		    		out.put((byte)(Integer.parseInt(new String(chars), 16) & 0xff));
		    		return CoderResult.UNDERFLOW;
		    	}

		    };
		}

		@Override
		public CharsetDecoder newDecoder() {
			return new FixedDecoder(this, 1, 2, 2) {
		
				@Override
				public void decode(CharBuffer out) {
					byte b = this.bb.get();
					try {
						toHex(out, b);
					} catch (IOException e) {
						throw new TeiidRuntimeException(e);
					}
				}

			};
		}
		
		@Override
		public boolean contains(Charset cs) {
			return false;
		}
	};

	public static void toHex(Appendable out, byte b) throws IOException {
		out.append(hex_alphabet[(b & 0xf0) >> 4]);
		out.append(hex_alphabet[b & 0x0f]);
	}
	
	public static final String BASE64_NAME = "BASE64"; //$NON-NLS-1$
	public static final Charset BASE64 = new Charset(BASE64_NAME, new String[0]) {
		@Override
		public CharsetEncoder newEncoder() {
			return new FixedEncoder(this, 4, .75f, 1) {

		    	@Override
		    	protected CoderResult encode(ByteBuffer out) {
		    		try {
		    			out.put(Base64.decode(cb));
		    			return CoderResult.UNDERFLOW;
		    		} catch (IllegalArgumentException e) {
		    			return CoderResult.unmappableForLength(4);
		    		}
		    	}

		    };
		}

		@Override
		public CharsetDecoder newDecoder() {
			return new FixedDecoder(this, 3, 1.25f, 3) {
		
				@Override
				public void decode(CharBuffer out) {
					if (bb.limit() == bb.array().length) {
						out.put(Base64.encodeBytes(bb.array()));
					} else {
						out.put(Base64.encodeBytes(Arrays.copyOf(bb.array(), bb.limit())));
					}
				}
			};
		}

		@Override
		public boolean contains(Charset cs) {
			return false;
		}
	};

	/*
	 * http://www.docjar.com/html/api/sun/nio/cs/UTF_32Coder.java.html
	 */
	public static final String UFT_8_BOM_NAME = "UTF-8-BOM"; //$NON-NLS-1$

	public static final Charset UTF_8_BOM = new Charset(UFT_8_BOM_NAME, new String[] {"UTF_8_BOM"}) { //$NON-NLS-1$

		@Override
		public CharsetEncoder newEncoder() {
			final CharsetEncoder ce = Streamable.CHARSET.newEncoder();
			return new CharsetEncoder(this, 1.1f, 3.0f, new byte[] {(byte)0xEF, (byte)0xBF, (byte)0xBD}) {
				boolean bom = true;

				@Override
				protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
					if (bom && in.hasRemaining()) {
						if (out.remaining() < 3) {
							return CoderResult.OVERFLOW;
						}
						out.put((byte)0xef);
						out.put((byte)0xbb);
						out.put((byte)0xbf);
						bom = false;
					}
					return ce.encode(in, out, false);
				}

				@Override
				protected void implOnMalformedInput(java.nio.charset.CodingErrorAction newAction) {
					ce.onMalformedInput(newAction);
				}

				@Override
				protected void implOnUnmappableCharacter(java.nio.charset.CodingErrorAction newAction) {
					ce.onUnmappableCharacter(newAction);
				}

				@Override
				protected void implReplaceWith(byte[] newReplacement) {
					ce.replaceWith(newReplacement);
				}

				@Override
				protected CoderResult implFlush(ByteBuffer out) {
					ce.encode(CharBuffer.allocate(0), out, true);
					return ce.flush(out);
				}

				@Override
				protected void implReset() {
					bom = true;
					ce.reset();
				}
			};
		}

		@Override
		public CharsetDecoder newDecoder() {
			return new Utf8BomDecoder(this);
		}
		
		class Utf8BomDecoder extends CharsetDecoder {
			private boolean bomProcessed = false;
			
			protected Utf8BomDecoder(Charset cs) {
				super(cs, 1.0f, 1.0f);
			}
			
			@Override
			protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
				// Handle BOM skipping first
				if (!bomProcessed) {
					if (in.remaining() >= 3) {
						// Peek at first 3 bytes to check for BOM
						int pos = in.position();
                        if ((in.get() & 0xFF) != 0xEF ||
                                (in.get() & 0xFF) != 0xBB ||
                                (in.get() & 0xFF) != 0xBF) {
                                    // No BOM, reset position
                                    in.position(pos);
                                }
                    }
					// If less than 3 bytes, no BOM possible, just continue
					bomProcessed = true;
				}

				// Now decode remaining as UTF-8
				return decodeUtf8Loop(in, out);
			}
			
			private CoderResult decodeUtf8Loop(ByteBuffer in, CharBuffer out) {
				while (in.hasRemaining() && out.hasRemaining()) {
					int b1 = in.get() & 0xFF;
					
					if (b1 <= 0x7F) {
						// 1-byte character
						out.put((char) b1);
					} else if ((b1 & 0xE0) == 0xC0) {
						// 2-byte character
						if (!in.hasRemaining()) {
							in.position(in.position() - 1);
							return CoderResult.UNDERFLOW;
						}
						int b2 = in.get() & 0xFF;
						if ((b2 & 0xC0) != 0x80) {
							return CoderResult.malformedForLength(1);
						}
						int codepoint = ((b1 & 0x1F) << 6) | (b2 & 0x3F);
						if (codepoint < 0x80) {
							return CoderResult.malformedForLength(2);
						}
						out.put((char) codepoint);
					} else if ((b1 & 0xF0) == 0xE0) {
						// 3-byte character
						if (in.remaining() < 2) {
							in.position(in.position() - 1);
							return CoderResult.UNDERFLOW;
						}
						int b2 = in.get() & 0xFF;
						int b3 = in.get() & 0xFF;
						if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
							return CoderResult.malformedForLength(1);
						}
						int codepoint = ((b1 & 0x0F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F);
						if (codepoint < 0x800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
							return CoderResult.malformedForLength(3);
						}
						out.put((char) codepoint);
					} else if ((b1 & 0xF8) == 0xF0) {
						// 4-byte character (surrogate pair)
						if (in.remaining() < 3) {
							in.position(in.position() - 1);
							return CoderResult.UNDERFLOW;
						}
						if (out.remaining() < 2) {
							in.position(in.position() - 1);
							return CoderResult.OVERFLOW;
						}
						int b2 = in.get() & 0xFF;
						int b3 = in.get() & 0xFF;
						int b4 = in.get() & 0xFF;
						if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80 || (b4 & 0xC0) != 0x80) {
							return CoderResult.malformedForLength(1);
						}
						int codepoint = ((b1 & 0x07) << 18) | ((b2 & 0x3F) << 12) | ((b3 & 0x3F) << 6) | (b4 & 0x3F);
						if (codepoint < 0x10000 || codepoint > 0x10FFFF) {
							return CoderResult.malformedForLength(4);
						}
						codepoint -= 0x10000;
						out.put((char) (0xD800 + (codepoint >> 10)));
						out.put((char) (0xDC00 + (codepoint & 0x3FF)));
					} else {
						// Invalid UTF-8 start byte
						return CoderResult.malformedForLength(1);
					}
				}
				
				if (in.hasRemaining() && !out.hasRemaining()) {
					return CoderResult.OVERFLOW;
				}
				
				return CoderResult.UNDERFLOW;
			}
			
			@Override
			protected void implReset() {
				bomProcessed = false;
			}
		}

		@Override
		public boolean contains(Charset cs) {
			return Streamable.CHARSET.contains(cs);
		}
	};

	public static abstract class FixedEncoder extends CharsetEncoder {

    	protected CharBuffer cb;
    	
    	protected FixedEncoder(Charset cs, int encodeChars, float averageBytesPerChar, float maxBytesPerChar) {
			super(cs, averageBytesPerChar, maxBytesPerChar); 
			cb = CharBuffer.wrap(new char[encodeChars]);
		}

		@Override
    	protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
		    while (in.hasRemaining()) {
	    		cb.put(in.get());
	    		if (!cb.hasRemaining()) {
					if (!out.hasRemaining()) {
					    return CoderResult.OVERFLOW;
					}
					cb.flip();
					CoderResult result = encode(out);
					if (result != CoderResult.UNDERFLOW) {
						return result;
					}
					cb.clear();
	    		}
		    }
		    return CoderResult.UNDERFLOW;
    	}

		abstract protected CoderResult encode(ByteBuffer out);
		
		@Override
		protected CoderResult implFlush(ByteBuffer out) {
			if (cb.position() != 0) {
				return CoderResult.unmappableForLength(cb.position());
			}
			return super.implFlush(out);
		}
		
		@Override
		protected void implReset() {
			cb.clear();
		}
				
    }
	
	public static abstract class FixedDecoder extends CharsetDecoder {

    	protected ByteBuffer bb;
    	
		protected FixedDecoder(Charset cs, int decodeBytes,
			     float averageCharsPerByte,
			     float maxCharsPerByte) {
			super(cs, averageCharsPerByte, maxCharsPerByte);
			this.bb = ByteBuffer.wrap(new byte[decodeBytes]);
		}

		@Override
		protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
		    while (in.hasRemaining()) {
	    		bb.put(in.get());
	    		if (!bb.hasRemaining()) {
					if (!out.hasRemaining()) {
					    return CoderResult.OVERFLOW;
					}
					bb.flip();
					decode(out);
					bb.clear();
	    		}
		    }
		    return CoderResult.UNDERFLOW;
		}

		protected abstract void decode(CharBuffer out);
		
		@Override
		protected CoderResult implFlush(CharBuffer out) {
			if (bb.position() != 0) {
				if (!out.hasRemaining()) {
				    return CoderResult.OVERFLOW;
				}
				bb.flip();
				decode(out);
				bb.clear();
			}
			return super.implFlush(out);
		}
		
		@Override
		protected void implReset() {
			bb.clear();
		}
    }

	public static Charset getCharset(String encoding) {
		if (BASE64_NAME.equalsIgnoreCase(encoding)) {
			return BASE64;
		}
		if (HEX_NAME.equalsIgnoreCase(encoding)) {
			return HEX;
		}
		if ("utf-8-bom".equalsIgnoreCase(encoding) || "utf_8_bom".equalsIgnoreCase(encoding)) { //$NON-NLS-1$ //$NON-NLS-2$
			return UTF_8_BOM;
		}
		return Charset.forName(encoding);
	}

	//standard icu charset detector from graalvm
	public static String guessEncoding(byte [] bytes) {
		CharsetDetector charsetDetector = new CharsetDetector();
		charsetDetector.setText(bytes);
		charsetDetector.enableInputFilter(true);
		CharsetMatch cm = charsetDetector.detect();
		return cm.getName();
	}
}
