/*
 * Copyright 2010 JBoss Inc
 *
 * 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 org.drools.examples.pacman

import java.awt.event.KeyEvent;

declare KeyEvent
    @role(event)
    @expires(0s)
end    


/**
 * Create a Direction for a character, based on a given keyCode. Return null
 * if the keyCode does not map to an arrow key.
 */
function Direction createDirection(Character character, KeyEvent keyCode) {
    DirectionEnum directionEnum;
    switch ( keyCode.getKeyCode() ) {    
        case 38 : { // UP
            directionEnum = DirectionEnum.UP;
            break;   
        }
        case 40 : { // DOWN
            directionEnum = DirectionEnum.DOWN;
            break;
        }
        case 37 : { // LEFT
        directionEnum = DirectionEnum.LEFT;
            break;
        }
        case 39 : { // RIGHT
            directionEnum = DirectionEnum.RIGHT;
            break;
        }
        default: {                
            return null;
        }
    }
    return Direction.newDirection( character, directionEnum );
}

/**
 * Only allow one KeyEvent at a time.
 */
rule KeyListenerRule dialect "mvel" when
    $keyEvent : KeyEvent() over window:length(1) from entry-point "KeyListener"
    $char     : Character( name == "Pacman" )
    $l        : Location( character == $char )
    $newD     : Direction() from createDirection( $l.character, $keyEvent )
    not Direction(character == $newD.character, horizontal == $newD.horizontal, vertical == $newD.vertical )
    $target   : Cell( row == ($l.row + $newD.vertical), col == ($l.col + $newD.horizontal) )
                CellContents( cell == $target, cellType != CellType.WALL )    
then
    exitPoints["ConsoleExitPoint" ].insert( "insert direction " + $newD + "\n" );   
    insert( $newD );
end

rule KeyEventCount dialect "mvel" salience -5 when
   $n : Number() from accumulate( 
           $keyEvent : KeyEvent() from entry-point "KeyListener",
            count( $keyEvent ) ) 
then
    System.out.println( "count : " + $n ) ;
end


/**
 * Retract all KeyEvents, ideally we should have expirs 0s, but that doesn't work
rule KeyListenerRuleRetractEvent dialect "mvel" salience -5 when
    $keyEvent : KeyEvent() from entry-point "KeyListener"
then
    retract( $keyEvent );
end
  */
