
package uk.ac.man.cs.lethe.internal.application.benchmarks


import java.io.File

import scala.io.Source




object CSVParser { 
  def parse(file: File): CSV = { 
    val lines = Source.fromFile(file).getLines()
    val keys = lines.next.split(",")
    val result = new CSV(keys)

    result.columns = lines.map(line => keys.zip(line.split(",")).toMap).toSeq

    result
  }
}



class CSV(keys: Seq[String]) { 
  
  var columns: Seq[Map[String,String]] = _


  def get(key: String, index: Int): String = {
    assert(keys.contains(key), "Key "+key+" not known")
    
    columns(index)(key)
  }


  def column(key: String): Seq[String] = 
    columns.map(_.apply(key))

  
  // Adds a column containing the index of each row
  // (May override an existing column)
  def addIndexColumn(key: String): CSV = { 
    val result = new CSV(keys:+key)

    result.columns = columns.indices.map(i => columns(i).updated(key, i.toString))

    result
  }



  // filters the elements where the key matches the value 
  def filter(key: String, value: String): CSV = 
    filter(key, Set(value))
  


  // filters the elements where the key matches one of the given values
  def filter(key: String, values: Set[String]): CSV = { 
    val result = new CSV(keys)
    result.columns = columns.filter(column => values.contains(column(key)))
    result
  }

  // filters out (removes) elements where the key matches one of the given values
  def filterOut(key: String, values: Set[String]): CSV = { 
    val result = new CSV(keys)
    result.columns = columns.filterNot(column => values.contains(column(key)))
    result
  }

  def size = columns.size

  def getKeys = keys
}
