#!/bin/bash

# to make the script fail safely
set -euo pipefail


out=${1:-output}

echo "" > $out

echo "Below is the feedback for your submission for alcohol.scala" >> $out
echo "" >> $out


# compilation tests

function scala_compile {
  (ulimit -t 30 -m 1024000 ; scala "$1" 2>> $out 1>> $out) 
}

# functional tests

function scala_assert {
  (ulimit -t 30 -m 1024000 ; scala -i "$1" "$2" -e "") #2> /dev/null 1> /dev/null)
}

# purity test

function scala_vars {
   (egrep '\bvar\b|\breturn\b|\.par|ListBuffer|mutable' "$1" 2> /dev/null 1> /dev/null)
}


# var, .par return, ListBuffer test
#
echo "alcohol.scala does not contain vars, returns etc?" >> $out

if (scala_vars alcohol.scala)
then
  echo "  --> fail" >> $out
  tsts0=$(( 1 ))
else
  echo "  --> success" >> $out
  tsts0=$(( 0 )) 
fi

### compilation test


if  [ $tsts0 -eq 0 ]
then 
  echo "alcohol.scala runs?" >> $out

  if (scala_compile alcohol.scala)
  then
    echo "  --> success" >> $out
    tsts=$(( 0 ))
  else
    echo "  --> scala did not run alcohol.scala" >> $out
    tsts=$(( 1 )) 
  fi
else
  tsts=$(( 1 ))     
fi

### alcohol tests

if [ $tsts -eq 0 ]
then
  echo "get_csv tests:" >> $out
  echo "  get_csv_page(url_alcohol).size == 194" >> $out
  echo "  get_csv_file(file_population).size == 216" >> $out

  if (scala_assert "alcohol.scala" "alcohol_test1.scala")
  then
    echo "  --> success" >> $out
  else
    echo "  --> one of the tests failed" >> $out
  fi
fi

### alcohol processing tests

if [ $tsts -eq 0 ]
then
  echo "processing tests:" >> $out  
  echo "  process_alcs(alcs_list.drop(1))(0) == (\"Afghanistan\", 0.0)" >> $out
  echo "  process_pops(pops_list.drop(1))(\"Micronesia\") == 104015" >> $out

  if (scala_assert "alcohol.scala" "alcohol_test2.scala") 
  then
    echo "  --> success" >> $out
  else
    echo "  --> one of the tests failed" >> $out
  fi
fi

### alcohol percentage tests

if [ $tsts -eq 0 ]
then
  echo "calculation tests:" >> $out  
  echo "  sorted_country_consumption().size == 177" >> $out
  echo "  sorted_country_consumption()(9) == (\"United Kingdom\", 671976864)" >> $out
  echo "  percentage(164) == (28771558364L, 28771558364L, 100.0)" >> $out
  
  if (scala_assert "alcohol.scala" "alcohol_test3.scala") 
  then
    echo "  --> success" >> $out
  else
    echo "  --> one of the tests failed" >> $out
  fi
fi

