require 'faraday'
require 'json'
require 'hashie'

module Brainspace
  class Collection
    def initialize(attributes)
      @mash = attributes
    end

    def method_missing(method_sym, *arguments, &block)
      @mash.send(method_sym, *arguments)
    end

    def discovery
      Brainspace::Collection.discovery(@mash.id)
    end

    def self.all
      response = Faraday.get("#{Brainspace.config.host}/collections", apikey: Brainspace.apikey)
      result = JSON.parse(response.body)
      collections = Hashie::Mash.new(result).collections
      collections.map { |collection| new(collection) }
    rescue
      []
    end

    def self.find(id)
      response = Faraday.get("#{Brainspace.config.host}/collections/#{id}", apikey: Brainspace.apikey)
      result = Hashie::Mash.new(JSON.parse(response.body))
      new(result.collection)
    rescue
      nil
    end

    def self.discovery(id)
      response = Faraday.get("#{Brainspace.config.host}/discovery/collection/#{id}", apikey: Brainspace.apikey)
      result = JSON.parse(response.body)
      articles = Hashie::Mash.new(result).data.article_results.articles
      articles.map { |article| Brainspace::Article.new(article) }
    rescue
      []
    end
  end
end
