#!/bin/bash

# download.sh
# downloading new levels



          ####################
          ## GLOBAL SECTION ##
          ####################



function download_menu () {
  if [ "$1" == "init" ]; then
    menu_title="Download new levels"
    menu_data="
    -Note: Make sure this program has access to the internet.
    -
    Browse levels archive ~ download_browse
    -Use this if you don't have any particular levelset in mind.
    -
    Search by name ~ debug_message todo_5
    -Use this if you know what's the name of the levelset you want.
    -
    Download by URL ~ download_url
    -Use this if you know the levelset's URL.
    -
    Download by RnD Files Archive by ID ~ debug_message todo_11
    -Use this if you know levelset's ID on RnD Files Archive.
    -
    Back to main menu ~ menu_back
    "
    return
  fi
}

function download_file () {
  header
  getfile $1
  [ "$failed" ] && return_to_main_menu && return
  echo " ## File downloaded. Importing ..."
  import $gotfile $2 $3
}

function download_url () {
  get_val " URL to download:"
  download_file $tmp
  menu_back
}



          #####################################
          ## "BROWSE LEVELS ARCHIVE" SECTION ##
          #####################################



function download_browse () {
  # get level category
  menu download_browse_category
  [ -z "$browse_category" ] && return
  
  # download level list
  header
  echo " ## Please wait, downloading levelsets list..."
  
  case $browse_category_id in
    0|2|5|6) # Additional Classic Levels, Classic Games, Multiplayer Levels, Tutorials; www.bd-fans.com
      bdfans_list_parse
      [ "$failed" ] && return
      bdfans_find_section $browse_category
      if [ -z "$sectionid" ]; then
        echo " ## Error: Couldn't find section '$browse_category'."
        return_to_main_menu && return
      fi
      menu download_browse_file
      [ -z "$download_id" ] || download_file ${browse_l_url[$download_id]} ${browse_l_sectname[$download_id]} ${browse_l_name[$download_id]}
      ;;
    1) # Additional Player Levels; www.elemu-project.de and www.bd-fans.com
      ;;
    3) # Contributions; www.artsoft.org and www.elemu-project.de/www.bd-fans.com
      ;;
    4) # Examples; www.zomis.net and www.bd-fans.com
      ;;
  esac
  
  menu_back
}

function download_browse_category () {
  if [ "$1" == "init" ]; then
    browse_category=
    browse_category_id=
    menu_title="Download new levels"
    menu_data="
    Additional Classic Levels
    Additional Player Levels
    Classic Games
    Contributions
    Examples
    Multiplayer Levels
    Tutorials
    -
    Cancel ~ menu_stop
    "
    return
  fi
  browse_category_id=$1
  browse_category="${menu_items[$1]}"
  menu_stop
}

function download_browse_file () {
  if [ "$1" == "init" ]; then
    local i mi=0
    menu_items[$((mi++))]="Back to main menu ~ menu_back"
    menu_title="Select file"
    for((i = 0; i < ${#browse_l_name[*]}; i++)); do
      if [ "${browse_l_sectname[$i]}" == "$browse_category" ]; then
        menu_items[$((mi++))]="-"
        menu_items[$((mi++))]="${browse_l_name[$i]} ~ download_browse_select $i"
        for item in ${browse_l_info[$i]}; do
          [ ! -z "$item" ] && menu_items[$((mi++))]="-$item"
        done
      fi
    done
    menu_items[$((mi++))]="-"
    menu_items[$((mi++))]="Back to main menu ~ menu_back"
  fi
}

function download_browse_select () { # args: URL
  download_id=$1
  menu_stop
}



          #############################
          ## WWW.BD-FANS.COM SECTION ##
          #############################



function bdfans_find_section () { # args: section name
  sectionid=
  for((i = 0; i < ${#bdfans_section_names[*]}; i++)); do
    [ "${bdfans_section_names[$i]}" == "$1" ] && sectionid=$i
  done
}

bdfans_already_parsed=""
function bdfans_list_parse () {
  local path begin end
  path="$tmp_dir/RnD.html"
  
  [ -f "$path" ] || getfile "http://www.bd-fans.com/RnD.html"
  if [ "$failed" ]; then
    echo "Press Enter to return to main menu."
    read x
    menu_back
    return
  fi
  
  [ -z "$bdfans_already_parsed" ] || return
  bdfans_already_parsed=true
  
  get_tmp_filename; bdfans_tmp_sections=$file
  get_tmp_filename; bdfans_tmp_data=$file
  get_tmp_filename; bdfans_tmp_sed1=$file
  get_tmp_filename; bdfans_tmp_sed2=$file
  
  # first, find the first occurence of <div class="tabletitle">
  begin=`grep -n -m 1 '<div class="tabletitle">' "$path"`
  begin=${begin%%:*}
  end=`grep -n -m 1 '<a name="Graphics">' "$path"`
  end=${end%%:*}
  
  # prepare sed scripts
  cat > $bdfans_tmp_sed1 <<HEREDOC
# this script performs most "transforming" tasks, like
# removing line wraps, empty lines and lines out of range

# don't use lines out of range $begin-$end
$begin,$end! d

$end s/^.*$/<EOF>/
$end! s/<EOF>//g

s/^ *//
/^$/ d

# remove line wraps
/[^>]$/ {
  \$b
  :b
  N
  /\n[^<]/ {
    s/\n/ /
    bb
  }
  P; D
}
HEREDOC
  cat > $bdfans_tmp_sed2 <<HEREDOC
# this script does minor tasks, like removing closing tags

# remove unneeded tags
s/<\/\?br[^>]*>//g
s/<\/\?img[^>]*>//g
s/<\/\?span[^>]*>//g
s/<\/\?table[^>]*>//g
s/<\/\?tbody[^>]*>//g
s/<\/t[rdh]>//g
/^$/ d

s/<td [^>]*>/<td>/
s/<th [^>]*>/<th>/

s/<td><a [^"]*"\([^"]*\)">/<td><a~\1~>/
/<td><a /! s/<\/\?a [^>]*>//g
s/<\/a>//g

s/&nbsp;/ /g
s/&uuml;/u/g
s/&ouml;/o/g
s/&amp;/\&/g

/<div class="tabletitle">/ {
  s/<\/div>//
  s/<div[^>]*>/<div>/
}

s/ *$//

HEREDOC
  
  sed -f $bdfans_tmp_sed1 $path | sed -f $bdfans_tmp_sed2 > $bdfans_tmp_data
  
  # make sections index
  grep -n '<div>' $bdfans_tmp_data | sed 's/<div>//g' > $bdfans_tmp_sections
  grep -n '<EOF>' $bdfans_tmp_data >> $bdfans_tmp_sections
  local i=0
  for section in $(< $bdfans_tmp_sections); do
    bdfans_section_names[$i]=${section#*:}
    bdfans_section_lines[$i]=${section%%:*}
    : $((i++))
  done
  local section=-1 levelsetid=-1
  local row col levelsetdata columndata headers
  for line in $(< $bdfans_tmp_data); do
    local data=$line tag=""
    if [ "${line:0:1}" == "<" ]; then
      data=${line#*>}
      tag=${line%%>*}
      tag=${tag:1}
    fi
    case $tag in
      div)
        : $((section++))
        row=-1
        unset headers
        ;;
      tr)
        : $((row++))
        col=-1
        levelsetdata=
        ;;
      th)
        headers[${#headers[*]}]=$data
        ;;
      td)
        : $((col++))
        if [ $col -eq 0 ]; then
          realdata=${data#*~>}; url=${data%~>*}; url=${url#*a~}
          : $((levelsetid++))
          browse_l_section[$levelsetid]=$section
          browse_l_sectname[$levelsetid]=${bdfans_section_names[$section]}
          browse_l_name[$levelsetid]=$realdata
          browse_l_url[$levelsetid]=$url
          browse_l_info[$levelsetid]=
        elif [ $((col+1)) -eq ${#headers[*]} ]; then
          [ -z "$data" ] || browse_l_info[$levelsetid]="${browse_l_info[$levelsetid]}$data$newline"
        else
          columndata=" ${headers[$col]}: $data"
          browse_l_info[$levelsetid]="${browse_l_info[$levelsetid]} ${headers[$col]}: $data$newline"
        fi
        ;;
      EOF)
        unset headers
        ;;
    esac
  done
}




