require 'active_record'
require 'rexml/document'
require 'net/http'
require 'uri'

module Cookbook
  module Acts
    module Dictionary

      def self.included(mod)
        mod.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_dictionary
          class_eval do
            extend Cookbook::Acts::Dictionary::SingletonMethods
          end
          include Cookbook::Acts::Dictionary::InstanceMethods
        end
      end

      module SingletonMethods
        def dictlist
          base = "http://services.aonaware.com"
          url = "#{base}/DictService/DictService.asmx/DictionaryList?"

          begin
            dict_xml = Net::HTTP.get URI.parse(url)
            doc = REXML::Document.new(dict_xml)

            dictionaries = []
            hash = {}
            doc.elements.each("//Dictionary/*") do |elem|
              if elem.name == "Id" 
                if !hash.empty?
                  dictionaries << hash 
                  hash = {}
                end
                hash[:id] = elem.text
              else
                hash[:name] = elem.text
              end
            end
            dictionaries
          rescue
            "error"
          end
        end
      end

      module InstanceMethods
        def define(dict='foldoc')

          base = "http://services.aonaware.com"
          url = "#{base}/DictService/DictService.asmx/DefineInDict"
          url << "?dictId=#{dict}&word=#{self.name}"

          begin
            dict_xml = Net::HTTP.get URI.parse(url)
            REXML::XPath.first(REXML::Document.new(dict_xml), 
              '//Definition/WordDefinition').text.gsub(/(\n|\s+)/,' ')
          rescue
            "no definition found"
          end
        end
      end

    end
  end
end

ActiveRecord::Base.class_eval do
  include Cookbook::Acts::Dictionary
end