#!/bin/bash

format=html
md='.md'
github_branch='version3.1'


if [[ 'html' == "$format"  ]]
then
  md=''
elif [[ 'md' == "$format" ]]
then
  md='.md'
elif [[ 'json' == "$format" ]]
then
  md='.json'
fi

if [ ! -e docs/api ]; then
  mkdir docs/api
fi

# descriptions of each module
desc_areautil='area utils, lat,lon point inside area'
desc_axisutil='draw title and axis labels'
desc_animatedseismograph='real time animated seismograph'
desc_components='simple web components'
desc_cssutil='simple util to inject css into web document'
desc_datalink='datalink protocol over web socket to a [Ringserver](https://seiscode.iris.washington.edu/projects/ringserver) datalink server'
desc_dataset='load/save seismic data as zip file'
desc_datechooser='widget to choose dates and times'
desc_distaz='calculates distance between to lat/lon points'
desc_fdsnavailability='query data availability from an FDSN availability web service'
desc_fdsncommon='common superclass for services following FDSN pattern'
desc_fdsndatacenters='query FDSN data center registry'
desc_fdsndataselect='query seismograms from an FDSN web service'
desc_fdsnevent='query earthquakes from an FDSN web service'
desc_fdsneventcomponent='html component for FDSN Event web service options'
desc_fdsnsourceid='parse FDSN sourceId'
desc_fdsnstation='query networks, stations and channels from an FDSN web service'
desc_fdsnstationcomponent='html component for FDSN Station web service options'
desc_fft='discrete fourier transforms via [OregonDSP](https://www.npmjs.com/package/oregondsp)'
desc_filter='timeseries filtering and utility functionality via [OregonDSP](https://www.npmjs.com/package/oregondsp)'
desc_handlebarshelpers='helpers for use with [handlebars](https://handlebarsjs.com/), eg in titles'
desc_helicorder='helicorder style 24 hour plots'
desc_infotable='component to display information about seismograms'
desc_irisfedcatalog='query IRIS fedcatalog web service'
desc_leaflet_css='standard css for leaflet'
desc_leafletutil='create leaflet maps with stations and earthquakes'
desc_miniseed='parsing miniseed files'
desc_mseed3='next generation miniseed file format for seismic data'
desc_mseed3eh='extra header parsing for mseed3'
desc_ms3ehtypes='autogenerated typescript types for bag extra headers in mseed3'
desc_mseedarchive='http access to remote miniseed files in a archive format'
desc_oregondsputil='utils for using the [OregonDSP](https://www.npmjs.com/package/oregondsp) package'
desc_organizeddisplay='organize more complex displays composed of individual pieces'
desc_particlemotion='plot of particle motion from seismograms'
desc_plotutil='utility functions for plotting'
desc_quakeml='objects corresponding to elements in a QuakeML xml file'
desc_ringserverweb='presentation of data pulled from the web interface of a [Ringserver](https://seiscode.iris.washington.edu/projects/ringserver)'
desc_sacpolezero='parsing of SAC polezero response file'
desc_scale='time and amplitude scale change notification'
desc_seedcodec='decompression for seismic data, often used from miniseed'
desc_seedlink='seedlink protocol over web socket to a [Ringserver](https://seiscode.iris.washington.edu/projects/ringserver) seedlink server'
desc_seedlink4='seedlink version 4 protocol over web socket to a [Ringserver](https://seiscode.iris.washington.edu/projects/ringserver) seedlink server'
desc_seismogram='objects representing seismograms and timeseries'
desc_seismogramloader='uses fdsnstation, fdsnevent, traveltime and fdsndataselect to load seismograms'
desc_seismogramsegment='objects representing contiguous segments of seismograms'
desc_seismograph='plotting of seismograms'
desc_seismographmarker='markers on seismograms'
desc_seismographutil='low level drawing functions for seismograph'
desc_seismographconfig='configuration of seismograph plots'
desc_seismographconfigeditor='editor for configuration of seismograph plots'
desc_sorting='sorting utilites for seismic data'
desc_spectraplot='plotting of specta output from the fft module'
desc_spelement='superclass for some custom elements'
desc_stationxml='objects corresponding to elements in a StationXML xml file'
desc_taper='tapering of timeseries'
desc_textformat='number formatting'
desc_transfer='instrument deconvolution of seismograms using response'
desc_traveltime='travel times of seismic waves via the IRIS traveltime web service'
desc_usgsgeojson='query and parse GeoJson from USGS'
desc_util='general utility functions'
desc_vector='vector process of seismograms'
desc_version='version of this library'
desc_luxon='the [luxon](https://moment.github.io/luxon/) library, for easy access'

if [ -e README_part.md ]; then
  rm README_part.md
fi


if [[ 'html' == "$format"  ]]
then
# top of index.html
cat > docs/api/index.html <<EOF
<html>
  <head>
    <meta charset='utf-8'>
    <title>Seisplotjs 3.1 API Documentation</title>
    <meta name='description' content='Javascript library for parsing, manipulating and displaying seismic data.'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>
    <link href='../api/assets/bass.css' rel='stylesheet'>
    <link href='../api/assets/split.css' rel='stylesheet'>
    <link rel="icon" type="image/png" href="../../flavicon.png" />
  </head>
  <body>
    <div class='flex'>
      <div id='split-left' class='overflow-auto fs0 height-viewport-100'>
        <div class='py1 px2'>
          <div id='toc'>
            <ul class='list-reset h5 py1-ul'>
              <li><a href="../index.html" class="">Seisplotjs</a></li>
              <li><a href="../api/index.html" class="">API JS Docs</a></li>
              <li><a href="../examples/index.html" class="">Examples</a></li>
              <li><a href="../gallery/index.html" class="">Gallery</a></li>
              <li><a href="../tutorial/index.html" class="">Tutorial</a></li>
            </ul>
          </div>
        </div>
      </div>
      <div id='split-right' class='relative overflow-auto height-viewport-100'>
              <section class='p2 mb2 clearfix bg-white minishadow'>
        <div class='clearfix'>

          <h3>Seisplotjs <span class="sp_version">3.1.4-alpha.1</span> API Documentation</h3>
          <p>Seisplotjs is a collection of javascript routines for requesting,
            manipulating and plotting seismic data. It is divided into submodules,
            which are listed below.
          </p>
          <ul>
EOF
fi

if [ -e docs/tutorial/8_andmore_part.html ]; then
  rm docs/tutorial/8_andmore_part.html
fi

for path in src/*.ts
do
  f=${path##*/}
  jsfile=${f%.ts}
  flowfile=${jsfile%.flow}
  if [  "${jsfile}" == "index_node" ]  || [ "${jsfile}" == "index" ]; then
    # skip index files
    continue
  fi
  if [ -e src/${jsfile}.ts ]
  then
    descText=""
    descArg=""
    descVarName="desc_${jsfile}"
    if [[ "${!descVarName}" ]]; then
      descText="${!descVarName}"
      descArg='--project-description'
    else
      echo "Missing Desc for ${jsfile} #################"
    fi
    # fix markdown style links with html
    re="(.*)\[(.+)\]\((.+)\)(.*)"
    descTextHtml="${descText}"
    while [[ $descTextHtml =~ $re ]]; do
      descTextHtml="${BASH_REMATCH[1]}<a href=\"${BASH_REMATCH[3]}\">${BASH_REMATCH[2]}</a>${BASH_REMATCH[4]}"
    done
    if [ 'index' != "$jsfile" ] && [ 'index_node' != "$jsfile" ]
    then
      #echo npx documentation build --parse-extension ts -f ${format} -o docs/api/${jsfile}${md} --document-exported --github  --project-name seisplotjs.${jsfile} src/${jsfile}.ts
      npx documentation build --parse-extension ts -f ${format} -o docs/api/${jsfile}${md} --document-exported --github  --project-name seisplotjs.${jsfile} src/${jsfile}.ts
      if [ $? -ne 0 ]
      then
        exit $?
      fi
      if [[ 'html' == "$format"  ]]
      then
        mv docs/api/${jsfile}/index.html docs/api/${jsfile}.html
      fi
      # modules links for README.md
      cat >> README_part.md <<EOF
  * [${jsfile}](https://crotwell.github.io/seisplotjs/api/${jsfile}.html) [(source)](https://github.com/crotwell/seisplotjs/blob/${github_branch}/src/${jsfile}.ts) ${descText}
EOF

    fi
  elif [ -d src/${jsfile} ]
  then
    echo
    echo WARN: doc script doesnot deal with subdirs in src yet
    echo
    #echo npx documentation build -f ${format} -o docs/api/${jsfile}${md} --document-exported --github --project-name seisplotjs.${jsfile} src/${jsfile}/[a-hj-z]*.ts
    #npx documentation build -f ${format} -o docs/api/${jsfile}${md} --document-exported --github --project-name seisplotjs.${jsfile} src/${jsfile}
  else
    echo unknown file ${f}
  fi
  if [[ 'html' == "$format" ]]
  then
    # entry of index.html
    cat >> docs/api/index.html <<EOF
      <li><a href="${jsfile}${md}.html">${jsfile}</a> ( <a href="https://github.com/crotwell/seisplotjs/blob/${github_branch}/src/${jsfile}.ts">source</a> ) - ${descTextHtml}</li>
EOF

    # also for tutorial8 "and more" entry of index.html
    cat >> docs/tutorial/8_andmore_part.html <<EOF
      <li><a href="../api/${jsfile}${md}.html">${jsfile}</a> ( <a href="https://github.com/crotwell/seisplotjs/blob/${github_branch}/src/${jsfile}.ts">source</a> ) - ${descTextHtml}</li>
EOF
  fi
done


if [[ 'html' == "$format" ]]
then
# bottom of index.html
cat >> docs/api/index.html <<EOF
          </ul>
        </div>
      </div>
    </div>
</body>
</html>
EOF
fi

# fix up links
python3 replaceInHtml.py

# copy assets
if [[ 'html' == "$format"  ]]
then
  rm -rf docs/api/assets
  mv docs/api/helicorder/assets docs/api/.
  cp docs/api/assets/bass.css docs/.
  cp docs/api/assets/split.css docs/.
  for f in src/*
  do
    jsfile=`basename ${f} .ts`
    if [ -d docs/api/${jsfile} ]
    then
      rm -r docs/api/${jsfile}
    fi
  done
fi
