<?
/**
 * CPMObjectEventHandler: CPMExample
 * Package: RN
 * Objects: Incident
 * Actions: Create, Update
 * Version: 1.3
 */
 
use \RightNow\CPM\v1 as RNCPM,
\RightNow\Connect\v1_3 as RNCPHP; //Connect version specified here must correspond with the version specified in Version in the flower basket

class CPMExample implements RNCPM\ObjectEventHandler
{
 
    /**
     * This is the main CPM function
     * @param int $runMode Indicates whether the CPM is being run live, or in test mode.
     * Possible values:
     * RNCPM\RunModeLive
     * RNCPM\RunModeTestObject
     * RNCPM\RunModeTestHarness
     * @param int $action Indicates whether the CPM is running for create, update, or destroy. 
     * Possible values: 
     * RNCPM\ActionCreate
     * RNCPM\ActionUpdate
     * RNCPM\ActionDestroy
     * @param object $object This is the Connect object that has been passed to the CPM to process.
     * It can be any Connect object that you have configured in the Objects part of the flower basket
     * @param int $cycles This keeps track of how many times the CPM has recursively run on this specific object.
     * Use the value passed here to prevent CPM loops, or to do a specific action on X cycles.
     */
    public static function apply($runMode, $action, $object, $cycles)
    {
        if($cycles > 0) return; //Prevents looping

        try{
            if($action == RNCPM\ActionCreate){
                $object->Subject = "Fresh Incident, Yum!";
            }
            else if($action == RNCPM\ActionUpdate){
                $object->Subject = "Leftovers are great too. Previous subject was: " . $object->prev->Subject;
            }
    
            if($runMode != RNCPM\RunModeLive){
                echo "This section will only run in the test harness, not in live use.\n";
            }
        }
        catch(Exception $e){
           static::sendErrors("Exception found on line {$e->getLine()}: {$e->getMessage()}");
        }
        catch(RNCPHP\ConnectAPIError $e){
            static::sendErrors("Exception found on line {$e->getLine()}: {$e->getMessage()}");
        }
    }

    public static function sendErrorMessage($msg = ""){

    }

    public static function sendErrors(){
        try{
            $mm = new RNCPHP\MailMessage();
            $mm->To->EmailAddresses = array([YOUR EMAIL HERE]);
            $mm->Subject = "CPM Error: CPMExample";
            
            $contentString = json_encode(debug_backtrace());
            $fattach = new RNCPHP\FileAttachment();
            $fattach->ContentType = "text/text";
            $fp = $fattach->makeFile();
            fwrite($fp, $contentString);
            fclose($fp);
            $fattach->FileName = "ExceptionData.txt";
            $fattach->Name = "ExceptionData.txt";
            
            $mm->FileAttachments = new RNCPHP\FileAttachmentArray();
            $mm->FileAttachments[] = $fattach;
           
            $mm->Body->Text = "Error running CPMExample";
            $mm->Body->Html = "Error running CPMExample";
            
            $mm->send();
        }
        catch(Exception $e){
           echo "Exception sending exceptions email; there's some irony for you. {$e->getLine()}: {$e->getMessage()}";
        }
        catch(RNCPHP\ConnectAPIError $e){
            echo "Exception sending exceptions email; there's some irony for you. {$e->getLine()}: {$e->getMessage()}";
        }
    
    }
}
 
class CPMExample_TestHarness implements RNCPM\ObjectEventHandler_TestHarness
{
    private static $testIncident;
    /**
     * This function runs once per test, before any of the other functions.
     * It is typically used to create test objects, or any other one-time-only setup.
     */
    public static function setup()
    {
        $contact = new RNCPHP\Contact();
        $contact->Name = new RNCPHP\PersonName();
        $contact->Name->First = "Malcolm";
        $contact->Name->Last = "Reynolds";
        $contact->save();

        $incident = new RNCPHP\Incident();
        $incident->PrimaryContact = $contact;
        $incident->Subject = "Test Incident";

        static::$testIncident = $incident;
    }
 
    /**
     * This function runs after setup(). It will run once for each type of object and each type
     * of action as configured in the Objects and Actions sections of the flower basket.
     * Example: If you have two Objects and two Actions configured, this function will run four times. 
     * @param int $action Indicates whether a create, update, or destroy action is being tested. 
     * Possible values: 
     * RNCPM\ActionCreate
     * RNCPM\ActionUpdate
     * RNCPM\ActionDestroy
     * @param class $objectType Indicates which object type is being tested. 
     * @return mixed Return a Connect object of the expected type. This object will 
     * be processed through the apply() function. 
     * You can also pass an array of Connect objects, in which case each item in the array
     * will separately pass through the apply() function. 
     */
    public static function fetchObject($action, $objectType)
    {
        $config = RNCPHP\Configuration::fetch('CUSTOM_CFG_CPM_TEST_ID');
        $id = $config->Value;

        $testObject = RNCPHP\Incident::fetch($id);

        $testObjects = array($testObject, static::$testIncident);

        return $testObjects; //Returning an array of objects will cause the apply function to run on each object in the array.
    }
 
    /**
     * This function runs after the apply() function has run on whatever objects were returned
     * from the fetchObject() function.
     * @param int $action Indicates whether a create, update, or destroy action is being tested. 
     * @param object $object The object that was passed to the apply function, after the apply function 
     * has been run on it.
     * @return boolean Return true to indicate testing success, false if you wish to show an error state.
     */
    public static function validate($action, $object)
    {
        $success = true;
        if($action == RNCPM\ActionCreate){
            $success = ($object->Subject == "Fresh Incident, Yum!");
            if($success){
                echo "Passed Create Test\n";
            }
            else {
                echo "Failed Create Test\n Subject was: {$object->Subject}\n";
            }
        }
        
        else if($action == RNCPM\ActionUpdate){
            $success = (strpos($object->Subject, "Leftovers are great too.") !== false);
            if($success){
                echo "Passed Update Test.\n";
            }
            else {
                echo "Failed Update Test\n Subject was: {$object->Subject}\n";
            }
        }

        return $success;
    }
 
    /**
     * This function runs once per validate() run.
     * Seldom used, except in cases where external data may have 
     * been modified during a test run (via external API calls, etc.)
     */
    public static function cleanup()
    {

    }
}