package com.javacodegeeks.console

import java.io.File
import java.io.PrintWriter
import java.net.URL

import scopt.OptionParser

import dispatch._
import dispatch.Defaults._
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.Source
import scala.language.postfixOps

object ConsoleApp extends App {
  val parser = new OptionParser[Configuration]("java -jar console-cli.jar") {
    override def showUsageOnError = true
    
    arg[String]("<url>")
      .required()
      .validate { url => Right(new URL(url)) }
      .action { (url, config) => config.copy(url = url) }
      .text("URL to fetch")
    
    opt[File]('o', "out")
      .optional()
      .valueName("<file>")
      .action((file, config) => config.copy(output = Some(file)))
      .text("optionally, the file to store the output (printed in console by default)")
      
    opt[Int]('t', "timeout")
      .required()
      .valueName("<seconds>")
      .validate { _ match {
          case t if t > 0 => Right(Unit)
          case _ => Left("timeout should be positive")
        }
      }
      .action((timeout, config) => config.copy(timeout = timeout))
      .text("timeout (in seconds) for waiting HTTP response")
      
    help("help")
      .text("prints the usage")
  }
  
  parser.parse(args, Configuration()) match {
    case Some(config) => { 
      val result = Await.result(Http(url(config.url) OK as.String), 
        config.timeout seconds)
        
      config.output match { 
        case Some(f) => new PrintWriter(f) {
          write(result)
          close
        }
        case None => println(result)
      }
      
      Http.shutdown()
    }  
    case _ => /* Do nothing, just terminate the application */
  }
}