require "./pixel.rb"

class PixelImage
  @@magickImg = nil

  @@pixels = []

  def initialize(i)
    @@magickImg = i
    @@width = @@magickImg.columns
    @@height = @@magickImg.rows

    self.buildPixels
  end

  def buildPixels
    tmp_pixels = @@magickImg.get_pixels(0, 0, @@width, @@height)

    for x in 0..@@width-1
      @@pixels[x] = []
      for y in 0..@@height-1
        @@pixels[x][y] = Pixel.new(tmp_pixels.pop)
      end
    end
  end

  # Only used for generating truly random base images
  def randomPixels
    for x in 0..@@width-1
      @@pixels[x] = []
      for y in 0..@@height-1
        pixel = 0

        r = rand(256)
        g = rand(256)
        b = rand(256)

        pixel = (pixel << 8) | r
        pixel = (pixel << 8) | g
        pixel = (pixel << 8) | b
        @@pixels[x][y] = Pixel.new(pixel)
      end
    end
  end

  def saveImage
    puts "and the mult is..."

    puts @@width * @@height

    pixel_array = []

    for x in @@pixels.reverse.each do
      for y in x.reverse.each do
        pix = y.getMagickPixel

        pixel_array.append(pix.red)
        pixel_array.append(pix.green)
        pixel_array.append(pix.blue)
      end
    end

    new_img = Magick::Image.new(@@width, @@height)


    new_img.import_pixels(0, 0, @@width, @@height, "RGB", pixel_array)

    new_img.write("arty_new.png")
  end

  def getPixels
    return @@pixels
  end

  def getPixel(x, y)
    return @@pixels[x][y]
  end

  def setPixelBits(x, y, bits)
    @@pixels[x][y] = Pixel.new(bits)
  end

  def getSize
    return {"width": @@width, "height": @@height}
  end

  def fuzzImage
    for x in 0..@@width-1 do
      for y in 0..@@height-1 do
        @@pixels[x][y].randomize
      end
    end
  end

  def getSalt
    salt = 0

    for x in 0..@@width-1
      for y in 0..@@height-1
        pix = @@pixels[x][y].getPixelBits

        salt = salt << 6 | ((pix >> 2) & 0b111111)
        pix = pix >> 8
        salt = salt << 6 | ((pix >> 2) & 0b111111)
        pix = pix >> 8
        salt = salt << 6 | ((pix >> 2) & 0b111111)
        pix = pix >> 8

      end
    end

    h = Digest::SHA512.hexdigest(salt.to_s(16))

    return h
  end

  def getBits(o)
    msg_bytes = o.unpack("c*")

    msg_bits = 0

    for b in msg_bytes
      msg_bits = (msg_bits << 8) | b
    end

    return msg_bits
  end
end