# The CareProvider class enables the following features:
# * Update care provider settings
# * Get a list of care providers
# * Search for a specific care provider based on key/value
class Caren::CareProvider < Caren::Base
      
  def self.keys
    [ :caren_id,                    # String (The id of this CP inside Caren)
      :name,                        # String
      :telephone,                   # String
      :website,                     # String
      :email,                       # String
      :address_line,                # String (Kerkstraat 1, 7522AH, Enschede)
      :url_shortcut,                # String
      :time_zone,                   # String (Amsterdam)
      :resolution,                  # String (exact,daypart,range)
      :bandwidth,                   # Integer (60 -> 60 minutes)
      :show_employee_names,         # Boolean
      :max_start,                   # String (23:00)
      :min_start,                   # String (07:00)
      :show_employee_name_as_title, # Boolean
      :communication                # Boolean
    ]
  end
    
  def self.search key, value
    from_xml Caren::Api.get( self.search_url(key,value) )
  end
  
  def self.all
    from_xml Caren::Api.get(self.resource_url)
  end
  
  def update
    Caren::Api.put(self.resource_url(self.caren_id), self.to_xml)
  end
  
  def update_logo logo_hash_or_path
    Caren::Api.put(self.resource_url(self.caren_id), self.to_logo_xml(logo_hash_or_path))
  end
    
  def as_xml
    { :name => self.name,
      :telephone => self.telephone,
      :website => self.website,
      :email => self.email,
      :address_line => self.address_line,
      :url_shortcut => self.url_shortcut,
      :time_zone => self.time_zone,
      :resolution => self.resolution,
      :bandwidth => self.bandwidth,
      :min_start => self.min_start,
      :max_start => self.max_start,
      :show_employee_name_as_title => self.show_employee_name_as_title,
      :show_employee_names => self.show_employee_names,
      :communication => self.communication }
  end
  
  def to_logo_xml logo_hash_or_path
    builder = Builder::XmlMarkup.new
    logo = self.class.logo_hash(logo_hash_or_path)
    xml = builder.care_provider do |care_provider|
      care_provider.tag!("logo", logo[:content], "name" => logo[:name], "content-type" => logo[:content_type] ) if logo
    end
  end
  
  def self.logo_hash logo_hash_or_path
    return logo_hash_or_path if logo_hash_or_path.is_a?(Hash)
    { :name => File.basename(logo_hash_or_path),
      :content => Base64.encode64(File.open(logo_hash_or_path).read),
      :content_type => `file -Ib #{logo_hash_or_path}`.gsub(/\n/,"").split(";")[0] }
  end
  
  def self.resource_location
    "/api/care_providers/"
  end
  
  def self.array_root
    :care_providers
  end
  
  def self.node_root
    :care_provider
  end
    
end