# redMine - project management software
# Copyright (C) 2006-2007  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

module Redmine
  module WikiFormatting
    module Macros
      module Definitions
        def exec_macro(name, obj, args)
          method_name = "macro_#{name}"
          send(method_name, obj, args) if respond_to?(method_name)
        end
      end
      
      @@available_macros = {}
      
      class << self
        # Called with a block to define additional macros.
        # Macro blocks accept 2 arguments:
        # * obj: the object that is rendered
        # * args: macro arguments
        # 
        # Plugins can use this method to define new macros:
        # 
        #   Redmine::WikiFormatting::Macros.register do
        #     desc "This is my macro"
        #     macro :my_macro do |obj, args|
        #       "My macro output"
        #     end
        #   end
        def register(&block)
          class_eval(&block) if block_given?
        end
        
        private
        # Defines a new macro with the given name and block.
        def macro(name, &block)
          name = name.to_sym if name.is_a?(String)
          @@available_macros[name] = @@desc || ''
          @@desc = nil
          raise "Can not create a macro without a block!" unless block_given?
          Definitions.send :define_method, "macro_#{name}".downcase, &block
        end
        
        # Sets description for the next macro to be defined
        def desc(txt)
          @@desc = txt
        end
      end
      
      # Builtin macros
      desc "Sample macro."
      macro :hello_world do |obj, args|
        "Hello world! Object: #{obj.class.name}, " + (args.empty? ? "Called with no argument." : "Arguments: #{args.join(', ')}")
      end
      
      desc "Displays a list of all available macros, including description if available."
      macro :macro_list do
        out = ''
        @@available_macros.keys.collect(&:to_s).sort.each do |macro|
          out << content_tag('dt', content_tag('code', macro))
          out << content_tag('dd', textilizable(@@available_macros[macro.to_sym]))
        end
        content_tag('dl', out)
      end
      
      desc "Displays a list of child pages."
      macro :child_pages do |obj, args|
        raise 'This macro applies to wiki pages only.' unless obj.is_a?(WikiContent)
        render_page_hierarchy(obj.page.descendants.group_by(&:parent_id), obj.page.id)
      end
      
      desc "Include a wiki page. Example:\n\n  !{{include(Foo)}}\n\nor to include a page of a specific project wiki:\n\n  !{{include(projectname:Foo)}}"
      macro :include do |obj, args|
        project = @project
        title = args.first.to_s
        if title =~ %r{^([^\:]+)\:(.*)$}
          project_identifier, title = $1, $2
          project = Project.find_by_identifier(project_identifier) || Project.find_by_name(project_identifier)
        end
        raise 'Unknow project' unless project && User.current.allowed_to?(:view_wiki_pages, project)
        raise 'No wiki for this project' unless !project.wiki.nil?
        page = project.wiki.find_page(title)
        raise "Page #{args.first} doesn't exist" unless page && page.content
        @included_wiki_pages ||= []
        raise 'Circular inclusion detected' if @included_wiki_pages.include?(page.title)
        @included_wiki_pages << page.title
        out = textilizable(page.content, :text, :attachments => page.attachments)
        @included_wiki_pages.pop
        out
      end
      
      #[[TitleIndex]]
      #
      #    Inserts an alphabetic list of all wiki pages into the output.
      #
      #    Accepts a prefix string as parameter: if provided, only pages with names that start with the prefix 
      #    are included in the resulting list. If this parameter is omitted, all pages are listed.
      #
      
      desc "Inserts an alphabetic list of all wiki pages into the output.  \n\n  !{{title_list(title-prefix)}}\n\n "
      macro :title_list do |obj, args|
        filter = "#{args.first}%"
        limit = 20 || args.second
        out = ''
        @pages = @wiki.pages.find(:all, 
                                  :conditions => ["#{WikiPage.table_name}.title like ?",filter],
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
        :order => 'title',
        :limit => limit)
        @pages.each do |page|
          out << content_tag('li',link_to(page.pretty_title, {:action => 'index',:page => page.title}))
        end
        content_tag('ul', out)
      end
      #
      # This generates a breadcrumb bar from a dash separated list of elements from page title
      # Analysis-UseCase-ManagingSamples => 3 level table of links
      #  
      #   {{#breadcrumb(title)}}
      #
      desc "split title as dash separates into also labeled links to parent pages  \n\n  !{{breadcrumb(title)}}\n\n "
      macro :breadcrumb do |obj, args|
        filter = "#{args.first}"
        crumbs =filter.split("-")
        crumbs = crumbs.each_index{|x|crumbs[x]="#{crumbs[x-1]}-#{crumbs[x]}" if x>0}.collect{|i|"'#{i}'"}
        @pages = @wiki.pages.find(:all, 
                                  :conditions => ["#{WikiPage.table_name}.title in (#{crumbs.join(',')})"],
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
        :order => 'title')
        out = []
        @pages.each do |page|
          text = page.title.split("-").last
          out << content_tag('span',link_to(WikiPage.pretty_title(text), {:action => 'index',:page => page.title}))
        end
        content_tag('p', out.join(">"),{:class=>'breadcrumb'})
      end
      #
      #  {{title_menu(prefix,depth,max,style)}}
      #  prefix for pages
      #  max number in menu defaults to 20
      #  css style to use defaults to toc
      #
      # Buils a Toc style menu out of child pages
      # This builds a vertial menu of items based on a prefix
      #
      #  {{title_menu(Analysis-UseCase-,10,'toc right')}}
      #
      # This would find all pages with the prefix 'title_menu(Analysis-UseCase-' and generate a toc right style menu of these
      # sorted by name with the prefix removed. limited to first 10 matches
      #
      desc "Inserts an alphabetic menu of all wiki pages into the output. \n\n  !{{title_menu(title-prefix,level,max,css-sytle)}}\n\n "
      macro :title_menu do |obj, args|
        filter = "#{args.first}"
        top = filter.count("-")
        depth=   args[1].to_i+1
        limit = args[2]||50
        style = args[3]||'toc'
        out = ''
        @pages = @wiki.pages.find(:all, 
                                  :conditions => ["#{WikiPage.table_name}.title like ?","#{filter}%"],
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
        :order => 'title')
        
        @pages.each do |page|
          elements = page.title.split("-")
          level = elements.size - top 
          level = elements.size - top -1
          text = (level>0 ? "-"*level : '')+ " "+ elements.last 
          text = text.gsub(/\_/," ")
          text = text.gsub(/([a-z])([A-Z])/,'\1 \2')
          unless level> depth
             out << content_tag('li',link_to(text, {:action => 'index',:page => page.title}))
          end
        end
        content_tag('ul', out,{:class=>style})
      end
      #
      #
      #  {{title_bar(prefix,depth,max,style)}}
      #  prefix for pages
      #  max number in menu defaults to 20
      #  css style to use defaults to toc
      #
      # Buils a single row table links to child pages
      #
      #  {{title_bar(Analysis-UseCase-,1exit,10,'table')}}
      #
      # This would find all pages with the prefix 'title_menu(Analysis-UseCase-' and generate a toc right style menu of these
      # sorted by name with the prefix removed. limited to first 10 matches
      #
      desc "Inserts an alphabetic menu of all wiki pages into the output.\n\n  !{{title_bar(title-prefix,level,max,css-sytle)}}\n\n "
      macro :title_bar do |obj, args|
        filter = "#{args.first}"
        top = filter.count("-")
        depth=   args[1].to_i+1
        limit =  args[2]||50
        style =  args[3]||'menu_bar'
        @pages = @wiki.pages.find(:all, 
                                  :conditions => ["#{WikiPage.table_name}.title like ?","#{filter}%"],
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
        :order => 'title',
        :limit => limit)
        cell = ""
        out = ''
        @pages.each do |page|
          elements = page.title.split("-")
          level = elements.size - top -1
          text = (level>0 ? "-"*level : '')+ " "+ elements.last 
          text = text.gsub(/\_/," ")
          text = text.gsub(/([a-z])([A-Z])/,'\1 \2')
          if level <= depth
             if level>= top 
               cell << content_tag('li',link_to(text, {:action => 'index',:page => page.title})) 
             else
               out << content_tag("td",content_tag("ul",cell,{:class=>style})) if cell.size>0
               cell = content_tag('li',link_to(text, {:action => 'index',:page => page.title})) 
             end
          end
        end
        out << content_tag("td",content_tag("ul",cell,{:class=>style})) if cell.size>0
        content_tag('table', content_tag("tr",out),{:class=>style})
      end

      
      desc "title_index  boxed up titles by letter to create a glossary or index \n\n  !{{title_menu(title-prefix,columns,max)}}\n\n "
      macro :title_index do |obj, args|
        filter = "#{args.first}"
        top = filter.count("-")
        columns =  args[1].to_i||4
        limit =  args[2]||1000
        style =  args[3]||'menu_bar'
        @pages = @wiki.pages.find(:all, 
                                  :conditions => ["#{WikiPage.table_name}.title like ?","#{filter}%"],
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
        :order => 'title',
        :limit => limit)
        cell = {}
        out = ''
        @pages.each do |page|
          text = page.title.split("-").last
          text[filter]='' if text[filter] 
          letter =text.first.upcase
          old ||= letter
          cell[letter] ||= ""
          cell[letter] << content_tag('li',link_to(WikiPage.pretty_title(text), {:action => 'index',:page => page.title})) 
        end
        row =""
        n=0
        for key in cell.keys.sort do
          row << content_tag("td",content_tag("strong",key) << content_tag("ul",cell[key],{:class=>style}),{:valign=>:top})
          n+=1
          if n>=columns
            out << content_tag("tr",row)
            row =""
            n=0
          end
        end  
        out << content_tag("tr",row) if row.size>0
        content_tag('table', content_tag("tr",out),{:class=>style})
      end

      #[[RecentChanges]] 
      #
      #    Lists all pages that have recently been modified, grouping them by the day they were last modified.
      #
      #    This macro accepts two parameters. The first is a prefix string: if provided, only pages with
      #     names that start with the prefix are included in the resulting list. If this parameter 
      #     is omitted, all pages are listed.
      #
      
      desc " Lists all pages that have recently been modified, grouping them by the day they were last modified"
      macro :recent_changes do |obj, args|
        filter = "#{args.first}%"
        limit = 5||args.second
        out = ''
        @pages = @wiki.pages.find(:all, 
                                  :conditions => ["#{WikiPage.table_name}.title like ?",filter],
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
        :order => "#{WikiContent.table_name}.updated_on desc",
        :limit => limit)
        @pages.each do |page|
          out << content_tag('li',link_to(page.pretty_title, {:action => 'index',:page => page.title}))
        end
        content_tag('ul', out)
      end

      
      #
      # Issues Lists
      #
      #
      desc "Lists Issues. Example:\n\n  !{{issue_list(tracker,category,status,user,max) }}\n\n"
      macro :issue_list do |obj, args|
        
        conditions=[]
        conditions << " trackers.name like '#{args[1]}%'"         unless args[0].blank?
        conditions << " issue_categories.name like '#{args[1]}%'" unless args[1].blank? 
        conditions << " issue_statuses.name like '#{args[2]}%'"   unless args[2].blank?
        conditions << " users.login like '#{args[3]}%'"   unless args[3].blank?
        limit = 10||args[3]
        out = ''
        @issues = @project.issues.find(:all, 
                                       :conditions => conditions.join(" and "),
        :include=>[:status,:tracker,:assigned_to,:category],:order=>'issues.id desc',:limit => limit)
        @issues.each do |issue|
          item = "<b>#{issue.id}</b> [#{issue.status.name}/#{issue.assigned_to.login}]  #{issue.subject}"
          out << content_tag('li',link_to(item, {:controller=>'issues',:action => 'show',:id => issue.id}))
        end
        content_tag('ul', out)
      end

      #
      # Free format issues query with name=value based parameter to filters to apply 
      #
      #
      desc "Query Issues. Example:\n\n  !{{issue_query(tracker=dddd&category=dsdd&status=dddd&owner=ssss&max=10) }}\n\n"
      macro :issue_query do |obj, args|
        params ={}
        args.collect do |v| 
          key,value = v.split("=")
          params[key] = value
        end
        conditions=[]
        conditions << " trackers.name like '#{params['tracker']}%'"         unless params['tracker'].blank?
        conditions << " issue_categories.name like '#{params['category']}%'"         unless params['category'].blank? 
        conditions << " issue_statuses.name like '#{params['status']}%'"   unless params['status'].blank?
        conditions << " users.login like '#params['owner']}%'"     unless params['owner'].blank?
        if params[:order]
          order =  params[:order] 
        else
          order = 'issues.id desc'
        end
        limit = 10 || params['max']
        out = ''
        @issues = @project.issues.find(:all, 
                                       :conditions => conditions.join(" and "),
        :order => order,
        :include=>[:status,:tracker,:assigned_to,:category],
        :limit => limit)
        
        @issues.each do |issue|
          item = "<b>#{issue.id}</b> [#{issue.status.name}/#{issue.assigned_to.login}]  #{issue.subject}"
          out << content_tag('li',link_to(item, {:controller=>'issues',:action => 'show',:id => issue.id}))
        end
        content_tag('ul', out)
      end
      #
      # Simple metre
      #
      desc "Count Issues. Example:\n  !{{issue_count(tracker=xxx,category=xxx,status=xxxx) }}\n\n "
      macro :issue_count do |obj, args|
        params ={}
        args.collect do |v| 
          key,value = v.split("=")
          params[key] = value
        end
        conditions=[]
        conditions << " trackers.name like '#{params['tracker']}%'"         unless params['tracker'].blank?
        conditions << " issue_categories.name like '#{params['category']}%'"         unless params['category'].blank? 
        conditions << " issue_statuses.name like '#{params['status']}%'"   unless params['status'].blank?
        conditions << " users.login like '#params['owner']}%'"     unless params['owner'].blank?
        
        num = @project.issues.count(
                                    :conditions => conditions.join(" and "),
        :include=>[:status,:tracker,:assigned_to,:category])             
        content_tag('b', "#{num}")
      end

      
    end
  end
end
