/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package cc.drx

/**
 * A tool to add launch commands to windows registry
 */
object Regedit{
  import Implicit.ec

  private def mkDefault(key:String,value:String):String              = s"[$key]\n@=" + value.quote
  private def rmKey(key:String):String                               = s"[-$key]"
  private def rmEntry(key:String, entry:String):String               = s"[$key]\n" + entry.quote + "=-"
  private def mkEntry(key:String, entry:String, value:String):String = s"[$key]\n" + entry.quote + "=" + value.quote

  private def mkCommand(cmd:File, args:Seq[String], ext:String="dir"):String = {
    val title = (cmd.basename +: args).mkSpaces
    val extApp = cmd.basename+"."+ext
    val root = ext match {
      case "." => s"HKEY_CLASSES_ROOT\\Directory"
      case "*" => s"HKEY_CLASSES_ROOT\\*"
      case _   => s"HKEY_CLASSES_ROOT\\$extApp"
    }
    val key = s"$root\\shell\\$title\\command"

    val cmds = cmd.canon.unixPath.replace("/","\\\\") +: args :+ "%1"

    def q(s:String):String = "\\\"" + s + "\\\""

    val byExt  = root endsWith extApp
    val extKey = s"HKEY_CLASSES_ROOT\\.$ext"
    val prefixKeys:Seq[String] = if(!byExt) Seq() else {
      Seq( mkDefault(extKey, extApp),  rmEntry(extKey, "NoOpen"))
    }
    (prefixKeys :+ mkDefault(key, cmds.map(q).mkSpaces)).mkString("\n\n")
  }

  def install(cmd:File, extArgPairs:Seq[(String,String)]) = {

    val contents = ("REGEDIT4" +: extArgPairs.map{case (ext, arg) =>
      mkCommand(cmd, arg.words.filter(_.isEmpty), ext) }
    ).mkString("\n\n")

    val f = cmd.companion("reg")
    f.out.println(contents)
    Shell("regedit", f.canon.path).run.blockWithoutWarning(5.minute)
  }
}