#encoding: utf-8
#- Name: SiSU
#
#  - Description: documents, structuring, processing, publishing, search
#    html
#
#  - Author: Ralph Amissah
#    <ralph.amissah@gmail.com>
#
#  - Copyright: (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
#    2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
#    2020, 2021, Ralph Amissah,
#    All Rights Reserved.
#
#  - License: GPL 3 or later:
#
#    SiSU, a framework for document structuring, publishing and search
#
#    Copyright (C) Ralph Amissah
#
#    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 3 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, see <http://www.gnu.org/licenses/>.
#
#    If you have Internet connection, the latest version of the GPL should be
#    available at these locations:
#    <http://www.fsf.org/licensing/licenses/gpl.html>
#    <http://www.gnu.org/licenses/gpl.html>
#
#    <http://www.sisudoc.org/sisu/en/manifest/gpl.fsf.html>
#
#  - SiSU uses:
#    - Standard SiSU markup syntax,
#    - Standard SiSU meta-markup syntax, and the
#    - Standard SiSU object citation numbering and system
#
#  - Homepages:
#    <http://www.sisudoc.org>
#
#  - Git
#    <https://git.sisudoc.org/projects/>
#    <https://git.sisudoc.org/projects/sisu>
#    <https://git.sisudoc.org/projects/sisu-markup>
require_relative 'dp'                                   # dp.rb
module SiSU_HTML_Tune
  require_relative 'se'                                 # se.rb
    include SiSU_Env; include SiSU_Screen
  require_relative 'html_parts'                         # html_parts.rb
  require_relative 'html_format'                        # html_format.rb #watch
  @@line_mode=''
  @@endnote_array=[]
  @@endnote_call_counter=1
  @@table_align='<table summary='' width="96%" border="0" cellpadding="0" col="3">
<tr ...><td width="2%" align="right">
&nbsp\;</td>
<td width="94%" valign="top" align="justify">'
  @@table_align_close='</td>
<td width="4%" align="right" valign="top">
<font size="1" color="#777777">
&nbsp;&nbsp;&nbsp;</font> </td></tr></table>'
  @@counter,@@column,@columns=0,0,0
  class Output
    def initialize(data,md)
      @data,@md=data,md
      @file=SiSU_Env::InfoFile.new(@md.fns)
      @cX=SiSU_Screen::Ansi.new(@md.opt.act[:color_state][:set]).cX
    end
    def hard_output
      @filename_tune=@file.write_file_processing.html_tune
      data=[]
      @data.each do |x|
        unless x.obj.empty?
          x.obj=x.obj.strip
          data << x
        end
      end
      data.each do |dob|
        @filename_tune.puts dob, "\n"
      end
    end
    def marshal
      File.open(@file.marshal.html_tune,'w') {|f| Marshal.dump(@data.to_a,f)}
    end
  end
  class CleanHTML
    def initialize(html='')
      @html=html
    end
    def clean_for_html
      html=@html
      str=if html.is_a?(String)
        html
      else html.obj
      end
      str=str.gsub(/#{Mx[:gl_o]}(#[0-9]{3})#{Mx[:gl_c]}/u,'&\1;').
        gsub(/#{Mx[:gl_o]}#([a-z]{2,4})#{Mx[:gl_c]}/u,'&\1;').
        gsub(/[<]/m,'&lt;').gsub(/[>]/m,'&gt;')
    end
    def clean
      html=@html
      str=if html.is_a?(String)
        html
      else html.obj
      end
      str=str.gsub(/#{Mx[:gl_o]}(#[0-9]{3})#{Mx[:gl_c]}/u,'&\1;').
        gsub(/#{Mx[:gl_o]}#([a-z]{2,4})#{Mx[:gl_c]}/u,'&\1;').
        gsub(/[\\]{2}/m,'<br>')
    end
  end
  class Tune
    include SiSU_Parts_HTML
    def initialize(data,md)
      @data,@md=data,md
      @sys=SiSU_Env::SystemCall.new
      @env=SiSU_Env::InfoEnv.new(@md.fns,@md)
    end
    def songsheet
      begin
        @cX=SiSU_Screen::Ansi.new(@md.opt.act[:color_state][:set]).cX
        if (@md.opt.act[:verbose][:set]==:on \
        || @md.opt.act[:verbose_plus][:set]==:on \
        || @md.opt.act[:maintenance][:set]==:on)
          SiSU_Screen::Ansi.new(@md.opt.act[:color_state][:set],'Tune').txt_grey
        end
        songsheet_array(@data)
        #data=songsheet_array(@data)
        if @md.opt.act[:maintenance][:set]==:on #Hard Output Tune Optional on/off here
          SiSU_HTML_Tune::Output.new(@data,@md).hard_output
          SiSU_HTML_Tune::Output.new(@data,@md).marshal
        end
        SiSU_HTML_Tune::Tune.new(@data,@md).output
      rescue
        SiSU_Errors::Rescued.new($!,$@,@md.opt.selections.str,@md.fns).location do
          __LINE__.to_s + ':' + __FILE__
        end
      ensure
      end
    end
    def songsheet_array(data)
      data_tuned=[]
      data.each do |dob|
        dob=amp_angle_brackets(dob)
        dob=endnotes_html(dob)
        dob=url_markup(dob)
        dob=markup(dob)
        data_tuned << dob
      end
      data_tuned
    end
    def urls(data)
      @words=data.each.map do |word|
        if word=~/#{Mx[:lnk_o]}(.+?)#{Mx[:lnk_c]}(?:#{Mx[:url_o]}\S+?#{Mx[:url_c]}|#{Mx[:rel_o]}\S+?#{Mx[:rel_c]}|image)/
          http_=true
          if word =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}#{Mx[:url_o]}\S+?#{Mx[:url_c]}/
            m,u=/#{Mx[:lnk_o]}(.+?)#{Mx[:lnk_c]}#{Mx[:url_o]}(\S+?)#{Mx[:url_c]}/.match(word).captures
          elsif word =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}#{Mx[:rel_o]}:\S+?#{Mx[:rel_c]}/
            #http_=false
            m,u=/#{Mx[:lnk_o]}(.+?)#{Mx[:lnk_c]}#{Mx[:rel_o]}:(\S+?)#{Mx[:rel_c]}/.match(word).captures
            u="#{Xx[:html_relative2]}/" + u
          elsif word =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}#{Mx[:rel_o]}\S+?#{Mx[:rel_c]}/
            http_=false
            m,u=/#{Mx[:lnk_o]}(.+?)#{Mx[:lnk_c]}#{Mx[:rel_o]}(\S+?)#{Mx[:rel_c]}/.match(word).captures
          elsif word =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}image/
            m,u=/#{Mx[:lnk_o]}(.+?)#{Mx[:lnk_c]}(image)/.match(word).captures
          end
          case m
          when /\.png|\.jpg|\.gif|c=|\s\d+x\d+/
            w,h=/\s(\d+)x(\d+)/.match(m).captures if m =~/\s\d+x\d+/
            w=%{width="#{w}"} if w
            h=%{height="#{h}"} if h
            c=m[/"(.+?)"/m,1]
            caption=%{<br><p class="caption">#{c}</p>} if c
            png=m.scan(/\S+/)[0]
            image_path=@md.file.output_path.html_seg.rel_image
            #image_path=(@md.fns =~/\.-ss[tm]$/) \
            #? @env.url.images_external
            #: @env.url.images_local
            ins=if u \
            and u.strip !~/^image$/
              %{<a href="#{u}"><img src="#{image_path}/#{png}" #{w} #{h} naturalsizeflag="0" align="bottom" border="0"></a>#{caption}}
            else %{<img src="#{image_path}/#{png}" #{w} #{h} naturalsizeflag="0" align="bottom" border="0">#{caption}}
            end
            word=word.gsub(/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}(?:#{Mx[:url_o]}\S+?#{Mx[:url_c]}|image)/,ins)
          else
            link=m[/(.+)/m]
            png=m.scan(/\S+/)[0].strip
            link=link.strip
            u=u.gsub(/(\S+)/,"#{Xx[:segment]}#\\1") if u !~/\// unless http_ #marker: in scroll remove; in seg replace
            ins=%{<a href="#{u}">#{link}</a>}
            word=word.gsub(/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}#{Mx[:url_o]}\S+?#{Mx[:url_c]}/,ins).
              gsub(/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}#{Mx[:rel_o]}\S+?#{Mx[:rel_c]}/,ins)
          end
          word
        else word
        end
      end.join(' ')
    end
    def url_markup(dob)
      unless dob.is==:code
        if dob.obj =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}(?:#{Mx[:url_o]}\S+?#{Mx[:url_c]}|#{Mx[:rel_o]}\S+?#{Mx[:rel_c]}|image)/
          @word_mode=dob.obj.scan(/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}(?:#{Mx[:url_o]}\S+?#{Mx[:url_c]}|#{Mx[:rel_o]}\S+?#{Mx[:rel_c]}|image)[()\[\]]*[,.;:!?'"]{0,2}|(?:#{Mx[:gl_o]}\S+?#{Mx[:gl_c]})+|[^#{Mx[:lnk_o]}#{Mx[:lnk_c]}]+/mu)
          words=urls(@word_mode)
          dob.obj=dob.obj.gsub(/.+/m,words)
        end #consider change, do a while loop
        dob.obj=dob.obj.gsub(/\\copyright/i,%{<sup>&copy;</sup>})
        if (dob.obj !~/\<:ad\s+\.\.\//)
          dob.obj=dob.obj.gsub(/\<:ad\s+(\S+)?\s+(\S+\.png)\s+(.+)?\;\s+(.+)?\;\s*!\>/,
            %{\n<center><a href="http:\/\/\\1" target="external"><img src="#{@env.url.images_local}/\\2" alt="\\3"></a></center>\n})
        else
          dob.obj=dob.obj.gsub(/\<:ad\s+(\S+)?\s+(\S+\.png)\s+(.+)?\;\s+(.+)?\;\s*\>/,
            %{\n<center><a href="\\1" target="_top"><img src="#{@env.url.images_local}/\\2" alt="\\3"></a></center>\n})
        end
        dob.obj=dob.obj.gsub(/!pick/,%{<img border="0" height="15" width="15" src="#{@env.url.images}/#{the_icon.i_choice}" alt="stellar">}).
          gsub(/!new/,%{&nbsp;<img border="0" height="15" width="15" src="#{@env.url.images}/#{the_icon.i_new}" alt="new">}).
          gsub(/<:h(.{1,7}?)>/,'<a href="#h\1">\1</a>').
          gsub(/<:to(\d{1,7}?)>/,'<a href="#to\1">to&nbsp;{&nbsp;\1&nbsp;}</a> ').
          gsub(/#{Mx[:url_o]}_(\S+?)#{Mx[:url_c]}/,'<a href="\1" target="_top">\1</a>'). #http ftp matches escaped, no decoration
          gsub(/#{Mx[:url_o]}([a-zA-Z0-9._-]+\@\S+?\.[a-zA-Z0-9._-]+)#{Mx[:url_c]}/,%{#{the_url_decoration.xml_open}<a href="mailto:\\1">\\1</a>#{the_url_decoration.xml_close}}).
          gsub(/#{Mx[:url_o]}(\S+?)#{Mx[:url_c]}/,%{#{the_url_decoration.xml_open}<a href="\\1" target="_top">\\1</a>#{the_url_decoration.xml_close}}) #http ftp matches with decoration
        if dob.obj =~/#{Xx[:html_relative2]}\/\S+/ \
        and dob.obj !~/(\"#{Xx[:html_relative2]}\/\S+?\"|>\s*#{Xx[:html_relative2]}\/\S+<)/
          dob.obj=dob.obj.gsub(/(#{Xx[:html_relative2]}\/\S+)/,'<a href="\1">\1</a>')
        end
        if dob.obj =~/..\/\S+/ \
        and dob.obj !~/(\"..\/\S+?\"|>\s*..\/\S+<)/
          dob.obj=dob.obj.gsub(/\.\.(\/\S+)/,%{<a href="#{Xx[:html_relative2]}\1">\1</a>})
        end
        dob.obj=dob.obj.gsub(/<a href=":/,%{<a href="#{the_url.site}/}).
          gsub(/<a href="\.\.\//,%{<a href="#{the_url.site}/}).
          gsub(/<a href="#{Xx[:html_relative2]}\//,%{<a href="#{the_url.site}/})
      else
        dob.obj=dob.obj.gsub(/</m,'&lt;').gsub(/>/m,'&gt;')
      end
      dob
    end
    def amp_angle_brackets(dob)
      dob.obj=dob.obj.
        gsub(/&/u,'&amp;').
        gsub(/<([a-z:\/]+)>/,"#{Dx[:lt_xml]}\\1#{Dx[:gt_xml]}").
        gsub(/</u,'&lt;').gsub(/>/u,'&gt;')
      dob
    end
    def endnotes_html(dob)
      unless dob.is ==:code
        dob.obj=dob.obj.gsub(/(#{Mx[:en_a_o]}|#{Mx[:en_b_o]})(\d+)\s+(.+?)(#{Mx[:en_a_c]}|#{Mx[:en_b_c]})/,
            %{&nbsp;<a href="##{Mx[:note]}\\2"><note id="#{Mx[:note_ref]}\\2">&nbsp;<sup>\\2</sup>&nbsp;</note></a> } +
            %{\\1\\2 <a href="##{Mx[:note_ref]}\\2"><note id="#{Mx[:note]}\\2">&nbsp;<sup>\\2.</sup></note></a> \\3 \\4}).
          gsub(/(#{Mx[:en_b_o]})([*+]\d+)\s+(.+?)(#{Mx[:en_b_c]})/,
            %{&nbsp;<a href="##{Mx[:note]}\\2"><note id="#{Mx[:note_ref]}\\2">&nbsp;<sup>\\2</sup>&nbsp;</note></a> } +
            %{\\1\\2 <a href="##{Mx[:note_ref]}\\2"><note id="#{Mx[:note]}\\2">&nbsp;<sup>\\2.</sup></note></a> \\3 \\4}).
          gsub(/(#{Mx[:en_a_o]})([*+]+)\s+(.+?)(#{Mx[:en_a_c]})/,
            %{&nbsp;<a href="##{Mx[:note]}\\2"><note id="#{Mx[:note_ref]}\\2">&nbsp;<sup>\\2</sup>&nbsp;</note></a> } +
            %{\\1\\2 <a href="##{Mx[:note_ref]}\\2"><note id="#{Mx[:note]}\\2">&nbsp;<sup>\\2</sup></note></a> \\3 \\4})
      end
      dob
    end
    def markup(dob)
      dob.obj=dob.obj.gsub(/#{Mx[:mk_o]}#([a-zA-Z]+)#{Mx[:mk_c]}/,'&\1;').
        gsub(/#{Mx[:mk_o]}(#[0-9]+)#{Mx[:mk_c]}/,'&\1;')
      dob.obj=dob.obj.gsub(/#{Mx[:br_line]}|#{Mx[:br_nl]}/,'<br>') unless dob.is==:table
      dob.obj=dob.obj.gsub(/#{Mx[:fa_bold_o]}(.+?)#{Mx[:fa_bold_c]}/,'<b>\1</b>').
        gsub(/#{Mx[:fa_italics_o]}(.+?)#{Mx[:fa_italics_c]}/,'<i>\1</i>').
        gsub(/#{Mx[:fa_underscore_o]}(.+?)#{Mx[:fa_underscore_c]}/,'<u>\1</u>').
        gsub(/#{Mx[:fa_superscript_o]}(.+?)#{Mx[:fa_superscript_c]}/,'<sup>\1</sup>').
        gsub(/#{Mx[:fa_subscript_o]}(.+?)#{Mx[:fa_subscript_c]}/,'<sub>\1</sub>').
        gsub(/#{Mx[:fa_insert_o]}(.+?)#{Mx[:fa_insert_c]}/,'<ins>\1</ins>').
        gsub(/#{Mx[:fa_cite_o]}(.+?)#{Mx[:fa_cite_c]}/,'<cite>\1</cite>').
        gsub(/#{Mx[:fa_strike_o]}(.+?)#{Mx[:fa_strike_c]}/,'<del>\1</del>').
        gsub(/#{Mx[:fa_monospace_o]}(.+?)#{Mx[:fa_monospace_c]}/,'<tt>\1</tt>'). # tt, kbd
        gsub(/#{Mx[:mk_o]}:name#(\S+?)#{Mx[:mk_c]}/,'<a name="\1"></a>').
        gsub(/#{Mx[:gl_bullet]}/m,'●&nbsp;&nbsp;').
        gsub(/#{Mx[:nbsp]}/,'&nbsp;').
        gsub(/<(p|br) \/>/,'<\1>')
      dob=SiSU_HTML_Tune::CleanHTML.new(dob).clean
      dob
    end
    def output
      data=@data
      @tuned_file=data.each.map do |dob|
        dob.obj=dob.obj.strip.chomp
        dob
      end
      @tuned_file << "\n<EOF>" if (@md.fns =~/\.sst0/) #remove
      @tuned_file
    end
  end
end
__END__
