namespace :export do
  EXCEPT = [:updated_at, :updated_by_id, :created_by_id, :created_at, :account_id, :tenant_id] # , :id, :version]

  def export(model)
    model.find_each do |view|
      attrs = view.attributes.symbolize_keys
      type = attrs.fetch(:type, model)
      puts "#{view.class}.create #{attrs.slice!(*EXCEPT).inspect}"
    end
  end

  namespace :bcms do
    desc "Export bcms stuff"
    task :default => [:export]

    task :export => :environment do
      puts "### Pages"
      export Page

      puts "### Dynamic Views"
      export DynamicView.scoped(:conditions => {:deleted => false})

      puts "### Attachments"
      export FileAttachment

      puts "### Html Blocks"
      export HtmlBlock.scoped(:conditions => {:deleted => false})

      puts "### Connectors"
      export Connector

      puts "### Sections"
      export Section

      puts "### Section Nodes"
      export SectionNode

    end

    task :cleanup => [:environment] do
    q = %{
select page_id, connectable_id, MAX(page_version) as page_version, MAX(connectable_version) as connectable_version from connectors
group by page_id, connectable_id
order by page_id, connectable_id, page_version DESC, connectable_version DESC
}
      versions = Connector.connection.select_all q
      deleted = versions.inject(0) do |deleted, hash|
        deleted + Connector.delete_all([ "(page_version < :page_version OR connectable_version < :connectable_version) AND (page_id = :page_id AND connectable_id = :connectable_id)", hash.symbolize_keys])
      end

      puts "Deleted #{deleted} connectors"
    end
  end

  task :bcms => ['bcms:export']

end
