require 'lib/sql_wrapper'
require 'json'

class IDMap
  attr_accessor :id
  attr_accessor :attributes
  attr_accessor :table

  def initialize(table, id=nil, id_field="id")
    @attributes = {}
    @id = -1 if id.nil?

    if @id != -1
      from_row(SQLWrapper.select(table, id, id_field))
    end
  end

  def create
    db = SQLWrapper.new
    map = {}
    @attributes.each_pair { |k,v| map[k] = db.quote(v) if not v.nil? }
    p map
    db.insert(@table, map)
    rows = db.rows("select last_insert_id() as id")
    @id = rows[0]['id']
  end

  def update(attrs)
    db = SQLWrapper.new
    attrs.reject! { |k,v| v.nil? }
    pairs = attrs.map { |k,v| "#{db.escape(k)} = #{db.quote(v)}" }.join(", ")
    sql = "UPDATE #{@table} set #{pairs} where id = #{@id}"
    attrs.each { |k,v| @attributes[k] = v }
    db.query(sql)
  end

  def delete!
    SQLWrapper.query("DELETE FROM #{@table} where id = #{@id} limit 1")
  end

  def save_file(tempfile, path)
    File.open(path, "wb") do |f|
      f.write(tempfile.read)
    end
    tempfile.close
    tempfile.unlink
  end

  def from_row(row)
    row.each do |k, v|
      @attributes[k] = v
    end

    @id = row['id'] if not row['id'].nil?
    return self
  end

  def get(key)
    @attributes[key]
  end

  def set(key, value)
    @attributes[key] = value
  end

  def to_json
    return self.to_map.to_json
  end

  def to_map
    obj = @attributes.dup
    obj['id'] = @id
    return obj
  end

  def valid?
    not @id.nil? and @id >= 0
  end
end
