package controllers

import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import java.security.MessageDigest

/*
 * Application sets a cookie in plain ASCII on the
 * clients browser recording the visits of a page.
 *
 * The cookie data is hashed and salted with a
 * secret key.
 */


object Application extends Controller {

  //secret key for salting - this key should not be
  //sent to the client; the key should normally be
  //a unguessable random number generated once
  val salt = "my secret key"

  //SHA-1 + salt
  def mk_hash(s: String) : String = {
    val hash_fun = MessageDigest.getInstance("SHA-1")
    hash_fun.digest((s + salt).getBytes).map{ "%02x".format(_) }.mkString
  }

  def gt_cookie(c: Option[Cookie]) : Int = 
    c.map(_.value.split("/")) match {
      case Some(Array(s, h)) 
        if (s.forall(_.isDigit) && mk_hash(s) == h) => s.toInt 
      case _ => 0
    }

  def mk_cookie(i: Int) : Cookie = {
    val s = i.toString
    Cookie("visits", s + "/" + mk_hash(s))
  }
   
  def index = Action { request =>

    val visits_cookie = request.cookies.get("visits")
    val visits = gt_cookie(visits_cookie)

    val msg1 = "You are a valued customer who has visited this site %d times."
    val msg2 = "You have visited this site %d times."
    val msg = 
      if (visits >= 10) msg1.format(visits) else msg2.format(visits)
    
    Ok(msg).as(HTML).withCookies(mk_cookie(visits + 1))
  }     
}




