/*
** DWVersionChecker
** 
** CHANGES:
** 0.2  (pozytron) Repaired version-checking system
** 0.21 (pozytron) Blocks custom messages by default
*/

#import "DWVersionChecker.h"


@implementation DWVersionChecker

#define kDWVersionCheckerDefaultsKey @"DWVersionChecker"
#define kAcqDownloadURL @"http://www.acqlite.org/?download"
#define defaults [NSUserDefaults standardUserDefaults]

/* Bundle Properties */

    + (NSString*) applicationVersion; {
        return [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleVersion"];
    }

    + (NSString*) applicationIdentifier; {
        return [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleIdentifier"];
    }

    + (NSString*) applicationName; {
        return [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleExecutable"];
    }


#pragma mark -
/* Initialization */

    + (id) sharedChecker; {
        static id checker = nil;
        if (!checker) checker = [[DWVersionChecker alloc] init];
        return checker;
    }
   
    - (id) init; {
        self = [super init];
        id string;

        string = [NSString stringWithFormat: @"http://www.acqlite.org/newversion.php?cv=%@", [DWVersionChecker applicationVersion]];
        
        [self setVersionURL: string];

        return self;
    }

    - (id) initWithVersionURL: (NSString*) vurl; {
        [self setVersionURL: vurl];
        return [self init];
    }

    - (void) setVersionURL: (NSString*) url; {
        [versionURL release];
        versionURL = [url retain];
    }
        

#pragma mark -
/* Actions */

    /* the file referenced by versionURL should contain a string of the format:
     *   {version}<br>{descriptionString}
     *   where {version} is the newest version, {descriptionString} is either "newest,"
     *   "older," or a description of the changes.
     */

    - (void) checkVersionUserInitiated: (BOOL) userInitiated; {
        [NSThread detachNewThreadSelector: @selector(checkVersionUserInitiatedThread:) toTarget: self withObject: [NSNumber numberWithBool: userInitiated]];
    }

    - (void) checkVersionUserInitiatedThread: (NSNumber*) theValue;
    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        if (versionURL) {
            NSArray*  info = [[NSString stringWithContentsOfURL: [NSURL URLWithString: versionURL]] componentsSeparatedByString: @"<br>"];
            
            if ([info count] > 1) {
                remoteVersion  = [[info objectAtIndex: 0] retain];
                descriptionString = [[info objectAtIndex: 1] retain];
                
                float rv = [remoteVersion floatValue];
                float lastIgnoredVersion = [defaults floatForKey: kDWVersionCheckerDefaultsKey];
                BOOL userInitiated = [theValue boolValue];
                
                if (rv > lastIgnoredVersion || userInitiated) {
                    if ([descriptionString isEqual:@"older"]) {
                        [self performSelectorOnMainThread: @selector(showUpdatePanel) withObject: nil waitUntilDone: NO];
                    } else if (userInitiated && [descriptionString isEqual:@"newest"]) {
                        [self performSelectorOnMainThread: @selector(showNoUpdatePanel) withObject: nil waitUntilDone: NO];
                    } else if (![descriptionString isEqual:@"newest"]) {
                        [self performSelectorOnMainThread: @selector(showCustomUpdatePanel) withObject: nil waitUntilDone: NO];
                    }
                }
            } else {
                NSLog(@"DWVersionChecker: Connection error.");
            }
        }
        [pool release];
    }


#pragma mark -
/* Panels */

    #define OK NSLocalizedStringFromTable(@"OK", @"DWVersionChecker", @"")
    #define DOWNLOAD NSLocalizedStringFromTable(@"Download...", @"DWVersionChecker", @"")
    #define LATER NSLocalizedStringFromTable(@"Remind Later", @"DWVersionChecker", @"")
    #define IGNORE NSLocalizedStringFromTable(@"Ignore", @"DWVersionChecker", @"")

    #define PU NSLocalizedStringFromTable(@"Version %@ is available to download.", @"DWVersionChecker", @"")
    #define SU NSLocalizedStringFromTable(@"You are using version %@ of %@. A newer release, version %@, is available.  For your own benefit and the benefit of all users on the network, it is strongly recommended that you download the new version.", @"DWVersionChecker", @"")

    - (void) showUpdatePanel; {
        int result = NSRunAlertPanel([NSString stringWithFormat: PU, remoteVersion], [NSString stringWithFormat: SU, [DWVersionChecker applicationVersion], [DWVersionChecker applicationName], remoteVersion], DOWNLOAD, IGNORE, LATER);
        
        if (result == 1) {	/* download */
            [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: kAcqDownloadURL]];
        }
        
        if (result == 0) {	/* ignore */
            [defaults setObject: remoteVersion forKey: kDWVersionCheckerDefaultsKey];
        }
        
        if (result == -1) {	/* remind later */
            [defaults setObject: nil forKey: kDWVersionCheckerDefaultsKey];
        }

        [defaults synchronize];
    }

    #define PNU NSLocalizedStringFromTable(@"This is the most recent version.", @"DWVersionChecker", @"")
    #define SNU NSLocalizedStringFromTable(@"Excellent! You are using the most recent release of %@, version %@. There is currently no need to upgrade.", @"DWVersionChecker", @"")

    - (void) showNoUpdatePanel; {
        NSRunAlertPanel(PNU, [NSString stringWithFormat: SNU, [DWVersionChecker applicationName], [DWVersionChecker applicationVersion]], OK, nil, nil);
    }
    
    - (void) showCustomUpdatePanel; {
        // The contents of the custom dialog are stored on a remote server.
        // Consequently, they are in English only. This is used to pipe text
        // about a VERY important update directly to the end user.
        
        int result = NSRunAlertPanel([NSString stringWithFormat: PU, [DWVersionChecker applicationVersion]], descriptionString, DOWNLOAD, IGNORE, LATER);
        
        if (result == 1) {	/* download */
            [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: kAcqDownloadURL]];
        }
        
        if (result == 0) {	/* ignore */
            [defaults setObject: remoteVersion forKey: kDWVersionCheckerDefaultsKey];
        }
        
        if (result == -1) {	/* remind later */
            [defaults setObject: nil forKey: kDWVersionCheckerDefaultsKey];
        }

        [defaults synchronize];
    }

@end