/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package cc.drx

object Base64{
  def encode(in:Array[Byte]):String = {
    val out = new StringBuilder()
    var b:Int = 0
    def add(b:Int) = out += Data.Radix64(b)
    val N:Int = in.length

    //https://en.wikipedia.org/wiki/Base64#Variants_summary_table
    for(i <- Range.inclusive(0,N) by 3){
        b = (in(i) & 0xFC) >> 2
        add(b)
        b = (in(i) & 0x03) << 4
        if (i + 1 < N)      {
            b |= (in(i + 1) & 0xF0) >> 4
            add(b)
            b = (in(i + 1) & 0x0F) << 2
            if (i + 2 < N)  {
                b |= (in(i + 2) & 0xC0) >> 6
                add(b)
                b = in(i + 2) & 0x3F
                add(b)
            } else  {
                add(b)
                out += '='
            }
        } else {
            add(b)
            out ++= "=="
        }
    }
    out.toString
  }
  private val Base64lookup = (0 to 255).toArray.map{i =>
    val c = i.toChar
    if(c == '=') -9 //equals padding
    else if (Data.Whitespace contains c) -5
    else Data.Radix64.indexOf(c)
  }

  def decode(in:String):Array[Byte] = {
    //https://en.wikipedia.org/wiki/Base64#Variants_summary_table
    val N = in.length
    if (N % 4 != 0) return Array[Byte]() //Failure("Invalid base64 input");

    val ieq = in.indexOf('=')
    val M = N*3/4 - (if(ieq > 0) N-ieq else 0)

    var decoded = Array.empty[Byte]

    def add(x:Int) = if(x >= 0) decoded :+= x.toByte

    var b = Array.ofDim[Int](4)

    var i = 0
    while(i < N){
        b(0) = Base64lookup(in(i+0))
        b(1) = Base64lookup(in(i+1))
        b(2) = Base64lookup(in(i+2))
        b(3) = Base64lookup(in(i+3))
        add((b(0) << 2) | (b(1) >> 4))
        if (b(2) < 64){
            add((b(1) << 4) | (b(2) >> 2))
            if (b(3) < 64)  add((b(2) << 6) | b(3))
        }
        i += 4
    }
    return decoded
  }
}