#!/usr/bin/env ruby

# coconut crab is copyright 2007 rawdod corporation and should 
# not be distributed under any circumstances

version = "1.2"

require 'yaml'
require "rexml/document"
require 'net/http'
require 'uri'

class CoconutCrabConfig
  
  attr_reader :apikey, :username, :apiurl, :downloaddir
  
  def initialize
    @homedir = `echo ~`.chomp
    @configfilename = "#{@homedir}/.coconutcrab"
    @apiurl = "http://www.coconutfunworld.com/xml/coconutapi.php"    
    read
  end
  
  def create
    print "Enter Coconutfunworld API key: "
    apikey = STDIN.gets.chomp
    print "Enter Coconutfunworld username: "
    username = STDIN.gets.chomp
    print "Enter Download Location [ #{@homedir}/Desktop/coconutfunworld ]: "
    downloaddir = STDIN.gets.chomp
    if downloaddir == ""
      downloaddir = "#{@homedir}/Desktop/coconutfunworld"
    end
    if username == nil
      username = "CoconutCrab User"
    end
    write(username, apikey, downloaddir)
    read
  end

  def read
    if File.exists? @configfilename
      coconutconfig = YAML::load(File.open(@configfilename))
      @username = coconutconfig.first
      @apikey = coconutconfig[1]
      @downloaddir = coconutconfig.last      
      puts "config loaded"
    else
      puts "no existing config file, creating one..."
      create
    end
  end
  
  def write(username, apikey, downloaddir)
    coconutconfig = [ username, apikey, downloaddir ]
    File.open(@configfilename, "w") { |configfile|
       configfile.puts coconutconfig.to_yaml
    }
  end

end

def menu
  puts ""
  puts "a) add image"
  puts "g) list gallerys"
  puts "d) download gallery"
  puts "l) list images in gallery"
  puts "i) download an image"
  puts "q) quit"
  print "coconutcrab> "
  option = STDIN.gets.chomp
  puts ""
  case option
  when "a"
     addimage
     menu
  when "g"
    getgalleries
    menu
  when "i"
    downloadimage(nil)
    menu
  when "l"
    listimages
    menu
  when "d"
    listimages(true)
    menu
  when "t"
    puts "get thumbs not implemented"
    menu
  when "q"
    puts "buh bye!"
  else
    puts "invalid command"
    menu
  end
end

def listimages(autodownload=false)
  method = "image.getthumbs"
  print "Enter Gallery id: "
  galleryid = STDIN.gets.chomp
  if autodownload == false
   print "Ask to download? [y,N]: "
   ask = STDIN.gets.chomp
  else
    galleryname = findgalleryname(galleryid)    
    puts "Downloading #{galleryname}"
  end
  cmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=" + method + "&galleryid=" + galleryid + "&page=1&resultsperpage=666"
  print "Listing images.... \n"
  url = URI.parse($coconutcrabconfig.apiurl)
  res = Net::HTTP.start(url.host, url.port) {|http|
    http.get(url.path + cmd)
  }
  galleries = REXML::Document.new res.body 
  galleries.elements.each("content/thumb") { |gallery|
    puts "[" + gallery.elements["imageid"].text + "] " + gallery.elements["imageurl"].text.split("/").last
    getimagecmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=image.getimage" + "&imageid=" + gallery.elements["imageid"].text
    imageres = Net::HTTP.start(url.host, url.port) {|http|
      http.get(url.path + getimagecmd)
    }
    image = REXML::Document.new imageres.body
    puts image.root.elements["description"].text unless image.root.elements["description"] == nil
    puts "by: " + image.root.elements["author"].text unless image.root.elements["author"].text == nil
    puts image.root.elements["width"].text + " x " + image.root.elements["height"].text unless image.root.elements["height"].text == nil || image.root.elements["width"].text == nil
    puts ""
    if ask == "y"
      print "Download? [y,N]: "
      getit = STDIN.gets.chomp
      if getit == "y" 
        downloadimage(gallery.elements["imageid"].text)
      end
    end
    if autodownload == true
      downloadimage(gallery.elements["imageid"].text, galleryname)
    end
    }
end

def downloadimage(imageid=nil, gallery=nil)
  method = "image.getimage"
  
  `mkdir -p #{$coconutcrabconfig.downloaddir}`
  
  if gallery != nil
    gallery.gsub!("'","")
    downloadplace = $coconutcrabconfig.downloaddir + "/" + gallery
    `mkdir -p #{downloadplace}`
  else
    downloadplace = $coconutcrabconfig.downloaddir
  end
  
  if imageid == nil
   print "Enter image id: "
   imageid = STDIN.gets.chomp
  end
  
  
  
  url = URI.parse($coconutcrabconfig.apiurl)
  getimagecmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=image.getimage" + "&imageid=" + imageid
  imageres = Net::HTTP.start(url.host, url.port) {|http|
    http.get(url.path + getimagecmd)
  }
  image = REXML::Document.new imageres.body
  imagename = image.root.elements['imageurl'].text.gsub(" ","%20").split("/").last
  puts "downloading #{imagename} to #{downloadplace}"
  puts ""
  
  imageurl = URI.parse(image.root.elements['imageurl'].text.gsub(" ","%20"))
  imagefile = Net::HTTP.start(imageurl.host, imageurl.port) {|http|
    http.get(imageurl.path)
  }
  File.open("#{downloadplace}/#{imagename}", "w") { |file|
    file.puts imagefile.body
  }
end

def getgalleries
  method = "image.getgallerys"
  cmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=" + method
  print "Getting galleries.... \n"
  url = URI.parse($coconutcrabconfig.apiurl)
  res = Net::HTTP.start(url.host, url.port) {|http|
    http.get(url.path + cmd)
  }
  galleries = REXML::Document.new res.body 
  galleries.elements.each("content/gallery") { |gallery|
    puts "[" + gallery.elements["galleryid"].text + "] " + gallery.elements["name"].text
    }
end

def findgalleryname(galleryid)
  method = "image.getgallerys"
  cmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=" + method
  url = URI.parse($coconutcrabconfig.apiurl)
  res = Net::HTTP.start(url.host, url.port) {|http|
    http.get(url.path + cmd)
  }
  galleryname = nil
  galleries = REXML::Document.new res.body 
  galleries.elements.each("content/gallery") { |gallery|
   if gallery.elements["galleryid"].text == galleryid
     galleryname = gallery.elements["name"].text.gsub(" ","_")
   end
  }
  return galleryname
end

def addimage
   method = "image.addimage"

   print "Enter image url: "
   imageurl = STDIN.gets
   imageurl.chop!

   if imageurl.scan(".jpg").length < 1 && imageurl.scan(".JPG").length < 1
    puts "\njpeg images only!\n"
    return 0
   end
   
   if imageurl.include? "&"
     puts "\napi cant handle image urls with & in them"
     return 0
   end

   print "Enter image description: "
   description = STDIN.gets
   description.chop!
   description = description.gsub("\b","")
  if imageurl && imageurl.length > 0
   cmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=" + method + "&imageurl="
   cmd << imageurl + "&description=" + description + "&author=" + $coconutcrabconfig.username
   cmd.gsub!(" ", "%20")
   print "Sending.... \n"
   url = URI.parse($coconutcrabconfig.apiurl)
   res = Net::HTTP.start(url.host, url.port) {|http|
     http.get(url.path + cmd)
   }
  newimage = REXML::Document.new res.body 
  print "Your image has been added!\n"
  # due to api breakage this wont work
  #imageid =  newimage.root.elements['imageid'].text
  #getimagecmd = "?apikey=" + $coconutcrabconfig.apikey + "&method=image.getimage" + "&imageid=" + imageid
  #imageres = Net::HTTP.start(url.host, url.port) {|http|
  #  http.get(url.path + getimagecmd)
  #}
  #image = REXML::Document.new imageres.body
  #puts "url is: " + image.root.elements['imageurl'].text
  #puts ""
  end
end

puts "welcome to coconutcrab #{version}"
$coconutcrabconfig = CoconutCrabConfig.new
menu
