//
//  Repository.m
//  MHP3SkillSim
//

#import "Repository.h"
#import "MHP3DataIO.h"
#import "PSBaseItems.h"
#import "PSItem.h"

@implementation Repository

@synthesize config = _config;
@synthesize items = _items;
@synthesize skillDB = _skillDB;
@synthesize color1 = _color1;
@synthesize color2 = _color2;
@synthesize resource = _resource;
@synthesize charmDB = _charmDB;
@synthesize fukugo = _fukugo;
@synthesize userFont = _userFont;
@synthesize myset = _myset;

+ (id)mainRepository
{
    static id _instance = nil;
    @synchronized(self) {
        if (!_instance) {
            _instance = [[self alloc]init];
        }
    }
    return _instance;
} 

- (id)init
{
    self = [ super init ];
    if (self) {
        _color1 = [UIColor whiteColor];
        _color2 = [UIColor colorWithRed:0.7 green:1.0 blue:0.7 alpha:1.0];
        _config = [[PSConfig alloc]init];
        _skillDB = [[SkillDB alloc] init];
        _items = [[PSBaseItems alloc] init];
        _resource = [[GameResource alloc]init];
        _fukugo = [[SkillFukugo alloc]init];
        _myset = [[PSMySet alloc]init];
        _charmDB = nil;
    }
    return self;
}

-(UIFont *)userFont {
    if (_userFont == nil) {
        _userFont = [UIFont boldSystemFontOfSize: 16];
    }
    return _userFont;
}

-(void)loadAll
{
    MHP3DataIO* reader = [[MHP3DataIO alloc] init];
    
    [reader readAll];
    [reader release];
    [_myset readFromDefaultFile];
    
    if (_myset.listCharms.count > 0) {
        Repository* repo = [Repository mainRepository];

        NSMutableArray* charms = repo.items.listCharm;
        NSMutableSet* already = [[NSMutableSet alloc]init];
        
        for (int i = 0; i < charms.count; ++ i) {
            PSItem* ch = [charms objectAtIndex:i];
            [already addObject:ch];
        }
        for (int i = 0; i < _myset.listCharms.count; ++ i) {
            PSItem* ch = [_myset.listCharms objectAtIndex:i];
            if ([already containsObject:ch]) {
                continue;
            }else {
                [already addObject:ch];
                [charms addObject:ch];
            }
        }
    }
}

-(void)dealloc
{
    [_config release];
    [_skillDB release];
    [_items release];
    [_charmDB release];
    [_myset release];
    [super dealloc];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    exit(0);
}

@end
