//
//  PropertyReader.m
//  ArmorP3V1
//

#import "PropertyReader.h"
#import "PSMutex.h"

@implementation PropertyReader

@synthesize properites = _properties;

- (id)init {
    self = [super init];
    if (self) {
        _properties = [[NSMutableDictionary alloc]init];
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(void)dealloc {
    [_properties release];
    [super dealloc];
}

- (BOOL) readFile : (NSString*) fileName {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@" , NSHomeDirectory(), fileName];
    
    if (filePath == nil) {
        NSException *exception = [[NSException alloc]initWithName:@"memoryerror" reason:@"nil" userInfo:nil];
        [exception raise];
    }
    
	if([fileManager fileExistsAtPath:filePath]) {
        //NSLog(@"open file %@", filePath);
    }else {
        NSBundle* bundle = [NSBundle mainBundle];
        //[filePath release];
        NSString* filePath2 = [bundle pathForResource: fileName ofType:nil];
        if (filePath2 == nil) {
            //NSLog(@"no file for %@", fileName);
            return FALSE;
        }
        filePath = filePath2;
        //NSLog(@"open file %@", filePath);
    }
    
    NSURL* url = [NSURL fileURLWithPath:filePath];
    NSError* error = [[NSError alloc]init];
    NSString* str = [NSString stringWithContentsOfURL:url encoding:NSShiftJISStringEncoding error: &error];
    
    BOOL ret = [self readFromString:str];
    //[str release];
    
    return ret;
}

- (BOOL) readPasteBoard {
    NSString* str = [UIPasteboard generalPasteboard].string;
    if (str != nil) {
        return [self readFromString:str];
    }
    return FALSE;
}

- (BOOL) readFromString:(NSString *)strContents {
    LineReader* reader = [[LineReader alloc]init];
    @try {
        [reader readFromString:strContents];
        return [self readFromLineReader:reader];
    }
    @catch (NSException *exception) {
    }
    @finally {
        [reader release];
    }
}

- (BOOL) readFromLineReader : (LineReader*) reader {
    while ([reader parseNextLine]) {
        NSString* str = reader.currentLine;
        if (str == nil) {
            continue;
        }
        int found = -1;
        for (int i = 0; i < str.length; ++ i) {
            int ch = [str characterAtIndex:i];
            if (ch == '=') {
                found = i;
                break;
            }
        }
        if (found > 0) {
            NSString* left = [str substringToIndex:found];
            NSString* right = [str substringFromIndex:found + 1];
            [_properties setObject:right forKey:left];
        }
    }
    return TRUE;
}

@end
