/*
   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.
*/
// vim: set ts=3 sw=3 et:

package cc.drx

object Clipboard{
  // import java.awt.datatransfer._
  import java.awt.datatransfer.DataFlavor
  import java.awt.{datatransfer=>jdt}

  private lazy val clipboard = java.awt.Toolkit.getDefaultToolkit.getSystemClipboard
  private def asString:String = Try(clipboard.getData(DataFlavor.stringFlavor).toString) getOrElse ""
  override def toString = asString

  def :=(str:String) = {Try{
     val selection = new jdt.StSelection(str)
     clipboard.setContents(selection,selection)
  }; this}
  def +=(str:String) = {this := toString + str; this}  //by return this, we can do folds to fill the clipboard
  def println(str:String) = this += str + "\n"
  /**set the clipboard value to the emptyString*/
  def empty = {this := ""; this}
  def apply(str:String) = this := str
  def apply(func: String => Unit) = {
     clipboard.addFlavorListener(new jdt.FlavorListener(){
        override def flavorsChanged(e:jdt.FlavorEvent) = func(asString)
     })
     clipboard
  }
  /**clear all active clipboard listeners*/
  def clear = for(f <- clipboard.getFlavorListeners) clipboard removeFlavorListener f//removal of all flavor listeners


  //--- copy image to clipboard
  // This class is used to hold an image while on the clipboard.
  class ImageSelection(image:java.awt.Image) extends jdt.Transferable {
    def getTransferDataFlavors:Array[DataFlavor] = Array(DataFlavor.imageFlavor)
    def isDataFlavorSupported(flavor:DataFlavor):Boolean = DataFlavor.imageFlavor.equals(flavor)

    // Returns image
    @throws(classOf[jdt.UnsupportedFlavorException])
    @throws(classOf[java.io.IOException])
    def getTransferData(flavor:DataFlavor):AnyRef = { //Note: getTransferData returns a java "Object" which is more accurately a scala "AnyRef" instead of a scala "Any"  (Scala 2.12 requies explict where 2.13 and 3.0 allowed for Any
      if(!isDataFlavorSupported(flavor)) throw new jdt.UnsupportedFlavorException(flavor)
      image
    }
  }

  private def systemClipboard = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard()

  def apply(image:java.awt.Image):Unit = {
    systemClipboard.setContents(new ImageSelection(Img.toRGB(image)), null); //force removal of alpha channel so stack traces are not printed to screen for debug
  }
  def apply(img:Img):Unit = apply(img.toAwt)
}