import java.util.concurrent.locks.ReentrantLock

val ReentrantLock transmitter = new ReentrantLock

rule "Single Plug"
  when
    Member of Gplugs received command
    // Item Power_Plug_Socket_1 received command or
    // Item Power_Plug_Socket_2 received command or
    // Item Power_Plug_Socket_3 received command or
    // Item Power_Plug_Socket_4 received command 
  then

    logInfo("Power_Plug", "Member " + triggeringItem.name + " to " + receivedCommand)
    
    try {
      // Lock transmitter so other executed rules dont't use it at the same time.
      // Concurrent calls of the rule will wait till the resource is free again.
      transmitter.lock()

      // Get the item which triggered the rule
      // Split the name and get the second part, the number to set as command.
      val num = triggeringItem.name.toString.split("Power_Plug_Socket_").get(1) 
      
      // Set the command which should be executed to the output channel 
      // Auto trigger will then execute the Thing.
      if(receivedCommand == ON){
        Remote_Send_Args.sendCommand("10010 " + num +" 1")
      }else{
        Remote_Send_Args.sendCommand("10010 " + num +" 0")
      }

      // Wait for the command to complete
      while(Remote_Send.state != OFF){
        Thread::sleep(100)
      }

      // Mulltiple trigger do not work if there is no break here
      // maybe external skript needs some time to properly free resources.
      Thread::sleep(400)
      logInfo("Power_Plug", Remote_Send_Out.state.toString.replaceAll("\r|\n"," ") )
    }catch(Throwable t) {}
    finally {
        // Free the resource for the next call.
        transmitter.unlock()
    }
 end