//
//  FSABundle.mm
//  F-Script Anywhere
//
//  Created by Nicholas Riley on Fri Feb 01 2002.
//  Copyright (c) 2002 Nicholas Riley. All rights reserved.
//

/*

 F-Script Anywhere is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 F-Script Anywhere is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with F-Script Anywhere; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

#include <Carbon/Carbon.h>
#include "SCPatchClient.h"
#include "SCPatchPrivate.h"
#include <stdio.h>
#import "FSAnywhere.h"
#import "FSAController.h"

class FSAPatchClient : public SCPatchClient
{
public:
    virtual OSErr Initialize(CFStringRef /* clientBundleID */, 
                             CFStringRef /* controllerBundleID */, 
                             pid_t /* pid */);
    virtual void ReceiveMessage(const AppleEvent * /* theAE */);
};

OSErr FSAPatchClient::Initialize(CFStringRef clientBundleID,
                                 CFStringRef controllerBundleID, 
                                 pid_t pid)
{
    FSALog(@"client = %@", (NSString *)clientBundleID);
    FSALog(@"controller = %@", (NSString *)controllerBundleID);
    [FSAController installMenu];
    return noErr;
}

void FSAPatchClient::ReceiveMessage(const AppleEvent *theAE)
{
    OSErr err = noErr;
    Size actualSize;
    DescType actualType;
    OSType eventClass, eventID;
    
    // XXX is this implementation even necessary?
    if ( (err = AEGetAttributePtr(theAE, keyEventIDAttr, typeType, &actualType, &eventID,
                                  sizeof(OSType), &actualSize)) != noErr)
        return;
    
    if ( (err = AEGetAttributePtr(theAE, keyEventClassAttr, typeType, &actualType,
                                  &eventClass, sizeof(OSType), &actualSize)) != noErr)
        return;
    
    if (eventClass == kSCMessageClass && eventID == kSCPing) {
        fprintf(stderr, "client received ping: sending reply...\n");
        SendMessage(mControllerBundleID, NULL, kSCMessageClass, kSCPing, "");
        fprintf(stderr, "reply sent\n");
    }
}

FSAPatchClient FSAPatchClientInstance;
SCPatchClient *SCPatchClient::sGlobalPatchClientInstance = &FSAPatchClientInstance;
