package code.snippet

import code.model.BackupDir

import _root_.net.liftweb.http.SHtml._
import _root_.net.liftweb.util.Helpers._
import _root_.net.liftweb.http.js.JE._
import _root_.net.liftweb.http.js.JsCmds._
import _root_.scala.xml.{NodeSeq, Text }
import net.liftweb.http.js.JsCmd
import net.liftweb.http.S
import code.util.Util._

/**
 * トップ画面（index.html）で使用するスニペットです。
 */
class IndexSnippet {

  def list(xhtml:NodeSeq):NodeSeq = {
    val dirList = BackupDir.findAll()

    <ul>
      {dirList.map(dir =>
        <li class={if(dirList.indexOf(dir) % 2 == 0) "odd" else "even"}>
          <div class="operation">
            <a href="javascript:void(0);" onclick={"openHistoryDialog('%s');".format(dir.directory)}>History</a>
            |
            <a href="javascript:void(0);" onclick={"openEditDialog(" + dir.id + ");"}>Edit</a>
            |
            {link("?id=" + dir.id, removeBackupDir, Text("Remove")) % ("onclick" -> "return confirmRemove(%d);".format(dir.id.get))}
          </div>
          <a href={"browse.html?root=" + u(dir.directory)}>
            <img src="images/package.png"/> <span id={"directory_" + dir.id}>{dir.directory}</span>
           </a>
          <div class="description" id={"description_" + dir.id}>{dir.description}</div>
        </li>)
      }
    </ul>
  }

  def addForm(xhtml:NodeSeq):NodeSeq = {
    ajaxForm(
      bind("form", xhtml,
        "submit" -> ajaxSubmit("Add", addBackupDir)
      )
    )
  }

  def editForm(xhtml:NodeSeq):NodeSeq = {
    ajaxForm(
      bind("form", xhtml,
        "submit" -> ajaxSubmit("Save", editBackupDir)
      )
    )
  }

  def removeBackupDir() = {
    val id = S.param("id").open_!.toLong
    val backupDir = BackupDir.findByKey(id).open_!
    backupDir.delete_!;
    S.redirectTo("/")
  }

  def addBackupDir() : JsCmd = {
    val backupDir = BackupDir.create
    backupDir.directory.set(S.param("directory").open_!)
    backupDir.description.set(S.param("description") .open_!)

    val errors = backupDir.validate
    if(errors.isEmpty){
      BackupDir.save(backupDir)
      JsRaw("location.reload();").cmd
    } else {
      // TODO 入力エラーの表示方法をなんとかする？
      Alert(errors(0).msg.text)
    }
  }

  def editBackupDir() : JsCmd = {
    val backupDir = BackupDir.findByKey(S.param("id").open_!.toLong).open_!
    backupDir.directory.set(S.param("directory").open_!)
    backupDir.description.set(S.param("description") .open_!)

    val errors = backupDir.validate
    if(errors.isEmpty){
      BackupDir.save(backupDir)
      JsRaw("location.reload();").cmd
    } else {
      // TODO 入力エラーの表示方法をなんとかする？
      Alert(errors(0).msg.text)
    }
  }
}