//
//  PSMutex.m
//  ArmorP3V1
//

#import "PSMutex.h"

@implementation PSMutex

@synthesize memoryAlert = _memoryAlert;
@synthesize stillWorkingAlert = _stillWorkingAlert;
@synthesize isRunnningTask = _isRunnningTask;
@synthesize isHaveMemoryAlert = _isHaveMemoryAlert;
@synthesize callStackForMemoryAlert = _callStackForMemoryAlert;

PSMutex* _instance = nil;

+(PSMutex*)mainMutex {
    return _instance;
}

+(void)createMainMutex {
    @synchronized([PSMutex class]) {
        if (_instance == nil) {
            _instance = [[PSMutex alloc]init];
        }
    }
}

-(id)init {
    self = [super init];
    if (self) {
        
        _memoryAlert = [UIAlertView alloc];
        [_memoryAlert initWithTitle:@"アラートです" message:@"メモリが不足しています" delegate:self cancelButtonTitle:@"終了" otherButtonTitles:nil];

        _stillWorkingAlert = [UIAlertView alloc];
        [_stillWorkingAlert initWithTitle:@"作業中です" message:@"少々おまちください" delegate:self cancelButtonTitle:@"終了" otherButtonTitles:@"待つ", nil];

        _isHaveMemoryAlert = FALSE;
        _isRunnningTask = FALSE;
        _callStackForMemoryAlert = nil;
    }else {
        abort();
    }
    return self;
}


-(BOOL)tryEnterTask {
    @synchronized([PSMutex class]) {
        if (_isRunnningTask) {
            return FALSE;
        }
        _isRunnningTask = TRUE;
        return TRUE;
    }
}

-(void)endTask {
    @synchronized([PSMutex class]) {
        if (_isRunnningTask) {
            _isRunnningTask = FALSE;
            return;
        }
        NSLog(@"endTask called when do nothing, stack = %@", [NSThread callStackSymbols]);
    }
}

-(void)showStillWorkingAlert {
    [_stillWorkingAlert show];
}

-(void)showMemoryAlertIfError {
    if (_isHaveMemoryAlert) {
        NSLog(@"alert for memory alert %@", _callStackForMemoryAlert);
        [_memoryAlert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"user abort = %@", [NSThread callStackSymbols]);
        abort();
    }else {
        NSLog(@"close");
    }
}

-(void)raiseMemoryError {
    if (_callStackForMemoryAlert == nil) {
        _callStackForMemoryAlert = [NSThread callStackSymbols];
    }
}

-(BOOL)isHaveMemoryAlert {
    return _callStackForMemoryAlert != nil ? TRUE : FALSE;
}

@end
