require_dependency "polyblock/application_controller"

module Polyblock
  class PolyblocksController < ApplicationController

    def update
      if params.key?(:pbs)
        params[:pbs].each do |i, attrs|
          next if attrs[:content].nil? ||
                  attrs[:content] == Polyblock::Block::DEFAULTS[:default_text]
          permitted_attrs = attrs.permit(:id, :name, :content, :_destroy)
          id = permitted_attrs.delete :id
          name = permitted_attrs[:name]
          matching_block = nil
          if id.present?
            matching_block = Block.find_by :id => id.to_i, :name => name
          end
          if name.present?
            matching_block ||= Block.find_by :name => name,
                                             :contentable => nil
          end
          if matching_block.present?
            matching_block.update_attributes!(permitted_attrs) 
          else
            Block.create! permitted_attrs
          end
        end
        render :text => "OK!"
      elsif params.key?(:polyblocks)
        params[:polyblocks].each do |name, pb_attrs|
          pb = Block.fetch_or_create name
          pb.update_attributes! pb_attrs
        end
        flash[:success] = 'Your polyblocks have been updated!'
        redirect_to :back
      end
    end

    # def convert_haml_to_html
    #   haml = params[:haml]
    #
    #   # Remove the pesky helpers
    #   haml = haml.split("= succeed \"")
    #   lines = [haml.shift]
    #   haml.each do |chunk|
    #     arg = chunk.split("\"",2)[0]
    #     block = chunk.split("\n")[1..-1].map{|line| line[2..-1]}.join("\n")
    #     lines << "#{block}\narg"
    #   end
    #   haml = lines.join("")
    #
    #   # Run it through the engine
    #   render :text => Haml::Engine.new(haml).render
    # end
    #
    # def convert_html_to_haml
    #   # html = if params.has_key? :cbid then ContentBlock.find(params[:cbid]).content else params[:html] end
    #   # engine = Html2haml::HTML.new html, :erb => false, :xhtml => false
    #   engine = Html2haml::HTML.new params[:html], :erb => false, :xhtml => false
    #   render :text => engine.render
    # end

  end
end