module Roughdraft

  def self.gist_pipeline(html, gist)
    context = {
      :gfm => true,
      :gist => gist,
      :asset_root => "http://#{RoughdraftApp::APP_DOMAIN}/images",
      :current_filetype => html.language.to_s
    }

    if html.language.to_s == 'Textile'
      filter = HTML::Pipeline::TextileFilter

    elsif html.language.to_s == 'Haml'
      filter = HTML::Pipeline::HamlFilter

    else
      filter = HTML::Pipeline::MarkdownFilter
    end

    pipe = HTML::Pipeline.new [
      filter,
      HTML::Pipeline::GistFilter,
      HTML::Pipeline::SanitizationFilter,
      HTML::Pipeline::ImageMaxWidthFilter,
      HTML::Pipeline::EmojiFilter
    ], context

    pipe.call(html.content.to_s)[:output].to_xhtml # return XHTML to be compatible with RSS
  end

  def self.gist_base_regex
    '(?:/)?([\w-]+)?/([\w]+)(?:-.)*'
  end

  def self.safe_html(string)
    context = {:whitelist => HTML::Pipeline::SanitizationFilter::FULL}
    pipe = HTML::Pipeline.new [HTML::Pipeline::SanitizationFilter], context

    pipe.call(string.to_s)[:output].to_s
  end

  def self.slugify_description(description)
    "-#{description.downcase.gsub(/\'|\"/, '').gsub(/[^\d\w]+|[_]+/, '-').gsub(/^-+|-+$/, '').gsub(/-{2,}/, '-')}"[0, 80] unless description == 'Generated by SassMeister.com.' || description.nil?
  end

  def self.url(owner, id, slug)
    "http://#{owner.downcase}.#{RoughdraftApp::APP_DOMAIN}/#{id}#{slug}"
  end
end
