module PagesHelper

  def parse_pp_tags(file)
    opened_file =  File.open(file)
    doc = Nokogiri::HTML(opened_file, nil, "UTF-8")
    opened_file.close
    pps = doc.css("*[data-pp]")
    pps.each do |pp|
      pp.content = "<p class='add-ps'></p>"
    end
    doc.to_html
  end

  def render_widget_for_frontend(controller_name, widget_method, widget_file, subpart_id=nil)
    def widget_parsing_repeats_again(elements,d,level)
        newhtml = []
        oldhtml = []
        elements.each do |el|
          html_to_render = ""
          data_name = el.attr("data-list")
          wrap_elements = el.css("*[data-list][data-level='#{level}']")
          if d["#{data_name}"]
            d["#{data_name}"].each_with_index do |item,i|
              element = el.inner_html
              if wrap_elements.count > 0
                htmls = widget_parsing_repeats_again(wrap_elements,d["#{data_name}"][i], level + 1)
                htmls[0].each_with_index do |html,i|
                  element = element.gsub(html,htmls[1][i])      
                end
              end
              item.each do |key,value|
                if !value.kind_of?(Array)
                  value = value.nil? ? "" : value
                  element = element.gsub("{{#{key}}}",value.to_s.html_safe)
                  element = element.gsub("%7B%7B#{key}%7D%7D",value.to_s)
                end
              end
              html_to_render = html_to_render + element
            end
            temp = el.to_s
            oldhtml << temp
            temp = temp.gsub(el.inner_html, html_to_render)
            newhtml << temp
          end
        end
        [oldhtml,newhtml]
      end
      @key = Site.first.template if @key.nil?
    controller_name = controller_name.downcase.singularize
    f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', "#{controller_name}", "_#{widget_file}.html.erb");
    if !File.exists?f
      f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'widgets', "#{controller_name}", "_#{widget_file}.html.erb");
      if !File.exists?f
        f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', "#{controller_name}", "_widget.html.erb");
        if File.exists?f
          f = File.join('../templates', "#{@key}", 'modules', "#{controller_name}", "_widget.html.erb");
        else
          return "<div class='well'>Maybe the administrator has changed the theme, please select the widget design again from the page settings.</div>".html_safe
        end
      else
        f = File.join('../templates', "#{@key}", 'widgets', "#{controller_name}", "_#{widget_file}.html.erb");
      end
    else
      f = File.join('../templates', "#{@key}", 'modules', "#{controller_name}", "_#{widget_file}.html.erb");
    end
    s = render_to_string(f)
    doc = Nokogiri::HTML(s, nil, "UTF-8")
    if !subpart_id.nil?
       doc.css("body").children.first.set_attribute("data-subpart-id", subpart_id) rescue nil
    end
    wrap_elements = doc.css("*[data-repeat]")
    controller = "#{controller_name.capitalize.pluralize}_controller".classify.constantize.new
    OrbitHelper.set_current_widget_module controller_name
    begin
      data = controller.send("#{widget_method}") #rescue nil
    rescue Exception => e
      write_widget_debug_file(e,controller_name,widget_method,subpart_id)
    end
    if !data.nil?
      wrap_elements = doc.css("*[data-list][data-level='0']")
      htmls = widget_parsing_repeats_again(wrap_elements,data,1)
      html = doc.to_s
      htmls[0].each_with_index do |h,i|
        html = html.gsub(h,htmls[1][i])
      end
      extras = data['extras'] || {}
      extras["widget-title"] = OrbitHelper.widget_title
      extras.each do |key,value|
        html = html.gsub("{{#{key}}}",value.to_s.html_safe)
        html = html.gsub("%7B%7B#{key}%7D%7D",value.to_s)
      end
      html.html_safe
    else
      return "<div class='well'>No content to show.</div>".html_safe
    end
  end

  def write_widget_debug_file(e,controller_name,action_name,sub_part)
      url_dir_name = request.fullpath.split("?")[0]
      url_dir_name = URI.decode(url_dir_name)
      url_dir_name = (url_dir_name  == "/" ? "home" : url_dir_name.sub("/","").gsub("/","_").gsub("-","_").gsub(" ","_"))
      directory_name = "tmp/debug/#{url_dir_name}"
      FileUtils.mkdir_p(directory_name) unless File.exists?(directory_name)
      fn = "#{directory_name}/#{controller_name}_#{action_name}_#{(sub_part if !sub_part.nil?)}.html"
      error_trace_spans = ""
      e.backtrace.each do |bt|
        error_trace_spans = error_trace_spans + "<span>#{bt}</span><br />"
      end
      con = "#{controller_name.capitalize.pluralize}_controller".classify.constantize
      File.open(fn, "w"){ |file| 
        file.puts "<html>
              <head>
                <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'>
                <meta charset=UTF-8'>
                <title>Debug result</title>
              </head>
              <body>
                <h3>Error Message</h3>
                <div class='error-message'>
                  <h2><i>#{e.message}</i></h2>
                </div>
                <h3>Request Details</h3>
                <div class='request-details'>
                  <span>Url : <b>#{URI.decode(request.url)}</b></span><br />
                  <span>Controller : <b>#{con.to_s}</b></span><br />
                  <span>Action : <b>#{action_name.capitalize}</b></span><br />
                  <span>SubPart Id : <b>#{sub_part}</b></span>
                </div>
                <h3>Error Trace</h3>
                <div class='error-trace'>
                  #{error_trace_spans}
                </div>
                <h3>Params</h3>
                <div class='params'>
                  #{OrbitHelper.params}
                </div>
              </body>
              </html>"

      }
    end

end