//
//  PSMySet.m
//  ArmorP3V1
//

#import "PSMySet.h"
#import "LineReader.h"
#import "PropertyReader.h"
#import "PSArmorSet.h"
#import "Repository.h"
#import "PSItem.h"
#import "PSWrap.h"
#import "CharmDB.h"
#import "PSMutex.h"

@implementation PSMySet

@synthesize listArmorSet = _listArmorSet;
@synthesize listCharms = _listCharms;

-(id)init {
    self = [super init];
    NSLog(@"init PSMySet");
    if (self) {
        _listArmorSet = [[NSMutableArray alloc]init];
        _listCharms = [[NSMutableArray alloc]init];
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(void)dealloc {
    NSLog(@"dealloc PSMySet");
    [_listArmorSet release];
    [_listCharms release];
    [super dealloc];
}

- (BOOL) readFromDefaultFile {
    LineReader* reader = [[LineReader alloc]init];
    @try {
        [reader readFile:@"PSMySet.ini"];
        return [self readFromLineReader:reader];
    }
    @catch (NSException *exception) {
        NSLog(@"exception %@ %@", exception, [exception callStackSymbols]);
    }
    @finally {
        [reader release];
    }
}

- (BOOL) readPasteBoard {
    LineReader* reader = [[LineReader alloc]init];
    @try {
        [reader readPasteBoard];
        return [self readFromLineReader:reader];
    }
    @catch (NSException *exception) {
        NSLog(@"exception %@ %@", exception, [exception callStackSymbols]);
    }
    @finally {
        [reader release];
    }
}

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

-(BOOL)readFromLineReader:(LineReader *)reader {
    PropertyReader* in = [[PropertyReader alloc] init];
    
    [_listArmorSet removeAllObjects];
    [_listCharms removeAllObjects];
   
    if ([in readFromLineReader:reader]) {
        NSMutableSet* mysetPre = [[NSMutableSet alloc]init];
        [mysetPre addObject:@"name"];
        [mysetPre addObject:@"picture"];
        [mysetPre addObject:@"hunterType"];
        [mysetPre addObject:@"genderType"];
        [mysetPre addObject:@"hunterRank"];
        [mysetPre addObject:@"townRank"];
        [mysetPre addObject:@"weaponSlotCount"];
        [mysetPre addObject:@"skill"];
        [mysetPre addObject:@"armor"];
        [mysetPre addObject:@"charmSkill"];
        [mysetPre addObject:@"charmSlot"];

        int number = 1;
        for (int i = 0; i < 10000; ++ i) {
            NSString* keyName = [[NSString alloc]initWithFormat:@"charm.%d.name", number];
            NSString* keySkill = [[NSString alloc]initWithFormat:@"charm.%d.skill", number];
            NSString* keySlot = [[NSString alloc]initWithFormat:@"charm.%d.slotCount", number];
            number++;
            
            NSString* valueName = [in.properites objectForKey:keyName];
            NSString* valueSkill = [in.properites objectForKey:keySkill];
            NSString* valueSlot = [in.properites objectForKey:keySlot];
            
            [keyName release];
            [keySkill release];
            [keySlot release];
            
            if (valueName == nil || valueSkill == nil || valueSlot == nil) {
                break;
            }
            
            int intSlot = -1;
            @try {
                intSlot = valueSlot.intValue;
            }
            @catch (NSException *exception) {
                NSLog(@"exception %@ %@", exception, [exception callStackSymbols]);
            }
            if (intSlot < 0) {
                NSLog(@"invalie skill for charm");
                break;
            }
            
            SkillSet* skill = [[SkillSet alloc]init];
            [LineReader StringToSkillSet:valueSkill: skill];
            
            PSItem* charm = [[PSItem alloc]init];
            [charm retain];
            charm.name = valueName;
            charm.skills = skill;
            charm.slotCount = intSlot;
            
            [_listCharms addObject: charm];
            [charm release];
        }  
        
        int counter = 1;

        for (int i = 1; i < 50000; ++ i) {
            NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];

            for (NSString* prefix2 in mysetPre) {
                NSString* key = [[NSString alloc]initWithFormat:@"myset.%d.%@", i, prefix2];
                NSString* value = [in.properites objectForKey:key];
                if (value == nil) {
                    [key release];
                    continue;
                }
                
                [dict setObject:value forKey:prefix2];
                [key release];
                [value release];
            }
            
            NSString* name = [dict objectForKey:@"name"];
            NSString* picture = [dict objectForKey:@"picture"];
            NSString* hunterType = [dict objectForKey:@"hunterType"];
            NSString* genderType = [dict objectForKey:@"genderType"];
            NSString* hunterRank = [dict objectForKey:@"hunterRank"];
            NSString* townRank = [dict objectForKey:@"townRank"];
            NSString* weapnSlotCount = [dict objectForKey:@"weaponSlotCount"];
            NSString* skill = [dict objectForKey:@"skill"];
            NSString* armor = [dict objectForKey:@"armor"];
            NSString* charmSkill = [dict objectForKey:@"charmSkill"];
            NSString* charmSlot = [dict objectForKey:@"charmSlot"];

            NSMutableArray* armorList = [[NSMutableArray alloc]init];
            
            [LineReader splitPerColumns:armor :armorList];
            
            PSArmorSet* set = [[PSArmorSet alloc]init];
            
            set.mysetNumber = counter ++;
            set.mysetName = name;
            set.mysetPicturePath = picture;
            set.hunterType = hunterType.intValue;
            set.hunterRank = hunterRank.intValue;
            set.townRank = townRank.intValue;
            set.genderType = genderType.intValue;
            set.townRank = townRank.intValue;
            set.weaponSlotCount = weapnSlotCount.intValue;
            
            SkillSet *skills = [[SkillSet alloc]init];
            [LineReader StringToSkillSet:skill :skills];
            set.targetSkills = skills;
            [skills release];
            
            skills = [[SkillSet alloc]init];
            [LineReader StringToSkillSet:charmSkill :skills];
            
            for (int itemType = 0; itemType < armorList.count; ++ itemType) {
                NSString* name = [armorList objectAtIndex:itemType];
                PSItem* found = nil;
                if (itemType != ITEM_TYPE_CHARM) {
                    found = [PSItem getInstanceByName:itemType : name];
                }
                if (found == nil && itemType == ITEM_TYPE_CHARM) {
                    found = [[PSItem alloc]init];
                    found.name = name;
                    found.itemType = ITEM_TYPE_CHARM;
                    found.skills = skills;
                    found.slotCount = charmSlot.intValue;
                    [_listCharms addObject:found];
                }
                
                PSWrap* wrap = [[PSWrap alloc]initWithItem:found :set.targetSkills];
                [wrap.maskedSkills set_only: found.skills];
                [set.listArmor addObject:wrap];
                [wrap release];
            }

            if (armorList.count <= 5) {
                break;
            }
            [_listArmorSet addObject:set];
            [set calculateUseList:FALSE];
            [skills release];
            [set release];
            [dict release];
        }
    }
    [self doUniqueCharms];
}

-(BOOL)writeProperties {
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@" , NSHomeDirectory(), @"PSMySet.ini"];
    NSString *filePathTmp = [NSString stringWithFormat:@"%@/Documents/%@_tmp", NSHomeDirectory(), @"PSMySet.ini"];

    int number = 1;
    NSMutableString* str = [[NSMutableString alloc]init];

    for (int i = 0; i < _listArmorSet.count;++ i) {
        PSArmorSet* set = [_listArmorSet objectAtIndex:i];
        NSString* prefix = [[NSString alloc]initWithFormat: @"myset.%d", number];
        number++;

        [str appendFormat:@"%@.name=%@\n", prefix, set.mysetName];
        [str appendFormat:@"%@.picture=%@\n", prefix, set.mysetPicturePath];
        [str appendFormat:@"%@.hunterType=%d\n", prefix, set.hunterType];
        [str appendFormat:@"%@.genderType=%d\n", prefix, set.genderType];
        [str appendFormat:@"%@.hunterRank=%d\n", prefix, set.hunterRank];
        [str appendFormat:@"%@.townRank=%d\n", prefix, set.townRank];
        [str appendFormat:@"%@.weaponSlotCount=%d\n", prefix, set.weaponSlotCount];

        [str appendFormat:@"%@.skill=", prefix];
        [LineReader SkillSetToString: set.targetSkills :str];
        [str appendFormat:@"\n"];

        [str appendFormat:@"%@.armor=", prefix];
        for (int i = 0; i < set.listArmor.count; ++ i) {
            if (i == 0) {
                
            }else {
                [str appendFormat:@","];
            }
            PSWrap* wrap = [set.listArmor objectAtIndex:i];
            [str appendFormat:@"%@", wrap.item.name];
        }
        [str appendFormat:@"\n"];
          
        Repository* repo = [Repository mainRepository];
        if (repo.resource.existCharm) {
            PSWrap* wrap = [set.listArmor objectAtIndex:ITEM_TYPE_CHARM]; 
            [str appendFormat:@"%@.charmSkill=", prefix];
            [LineReader SkillSetToString: wrap.item.skills: str];
            [str appendFormat:@"\n"];                
            [str appendFormat:@"%@.charmSlot=%d\n", prefix, wrap.item.slotCount];
        }
    }

    number = 1;
    for (int i = 0; i < _listCharms.count; ++ i) {
        PSItem* item = [_listCharms objectAtIndex:i];
        if (item.isVirtual) {
            continue;
        }
        NSString* prefix = [[NSString alloc]initWithFormat:@"charm.%d", number];
        number++;
        [str appendFormat:@"%@.name=%@\n", prefix, item.name];
        [str appendFormat:@"%@.skill=", prefix];
        [item.skills skillToString:str :nil :TRUE];
        [str appendString:@"\n"];
        [str appendFormat:@"%@.charmSlot=%d\n", prefix, item.slotCount];
        [prefix release];
    }  

    NSError *error = nil;
    [str writeToFile: filePathTmp atomically:YES encoding:NSShiftJISStringEncoding error:&error];
    if (error != nil) {
        NSLog(@"fileError1 = %@", error);
        [str release];
        return FALSE;
    }
    [str release];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    if ([fileMgr isReadableFileAtPath:filePath]) {
        [fileMgr removeItemAtPath:filePath error:&error];
        if (error != nil) {
            NSLog(@"fileError2 = %@", error);
            return FALSE;
        }
    }
    
    NSLog(@"renaming to %@", filePath);
    [fileMgr moveItemAtPath:filePathTmp toPath:filePath error:&error];
    if (error != nil) {
        NSLog(@"fileError3 = %@", error);
        return FALSE;
    }
    return TRUE;
}

-(void)doUniqueCharms {
    NSMutableArray* listFrom = _listCharms;
    
    if (listFrom == nil) {
        return;
    }

    NSMutableArray* listTo = [[NSMutableArray alloc]init];
    NSMutableSet* uniqSet = [[NSMutableSet alloc]init];

    for (PSItem* item in listFrom) {
        if ([uniqSet containsObject:item]) {
            continue;
        }
        [uniqSet addObject:item];
        [listTo addObject:item];
    }

    [_listCharms release];
    _listCharms = listTo;

    [uniqSet release];
}
@end
