//
//  TableControllerForArmorSet.m
//  ArmorP3V1
//

#import "TableControllerForArmorSet.h"
#import "Repository.h"
#import "PSWrap.h"
#import "DecorationSlot.h"
#import "DecorationMatcher.h"
#import "TableControllerForText.h"
#import "PSTableModel.h"
#import "ArmorP3V1AppDelegate.h"
#import "PSMutex.h"

@implementation TableControllerForArmorSet

@synthesize armorSet = _armorSet;
@synthesize listSlot = _listSlot;
@synthesize listTargetSkill = _listTargetSkill;
@synthesize footerView = _footerView;
@synthesize fromMyset = _fromMyset;

#define BUTTON_MIN   0
#define BUTTON_MYSET 0
#define BUTTON_TEXT  1
#define BUTTON_MAX   1

-(id)initWithArmorSet:(PSArmorSet *)item {
    self = [super initWithStyle: UITableViewStyleGrouped];
    if (self) {
        _armorSet = item;
        [_armorSet retain];
        _listTargetSkill = [_armorSet.targetSkills getNamedSkillNameForSearch];
        [_listTargetSkill retain];
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    
    _footerView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 1400, 100)];
    
    for(int i = BUTTON_MIN; i <= BUTTON_MAX; ++ i ){
        UIButton* button = [self createButton:i];
        [_footerView addSubview:button];
    }
    
    self.tableView.tableFooterView = _footerView;
}

-(UIButton *)createButton:(NSInteger)type {
    UIButton* button = nil;
    switch(type) {
        case BUTTON_MYSET:
            button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(0, 0, 280, 40);
            button.tag = type;
            if (_fromMyset) {
                [button setTitle:@"再度検索" forState:UIControlStateNormal];
            }else {
                [button setTitle:@"保存（マイセット）" forState:UIControlStateNormal];
            }
            button.backgroundColor = [UIColor clearColor];
            [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
            break;
        case BUTTON_TEXT:
            button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(0, 50, 280, 40);
            button.tag = type;
            [button setTitle:@"テキストでも表示" forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
            [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
            break;
    }
    return button;
}

- (IBAction)clickButton:(UIButton*)sender {
    switch(sender.tag) {
        case BUTTON_MYSET:
        {
            if (_fromMyset) {
                ArmorP3V1AppDelegate* delegate = [ArmorP3V1AppDelegate appInstance];

                UINavigationController *cont = delegate.naviForTop;
                UINavigationController *set = delegate.naviForSetting;

                [cont popToRootViewControllerAnimated:FALSE];
                [set popToRootViewControllerAnimated:FALSE];
                [delegate.tabBarController setSelectedIndex:0];
                
                Repository* repo = [Repository mainRepository];
                [repo.config.session.searchSkills set_all:_armorSet.targetSkills];
                if (_armorSet.genderType == 1 || _armorSet.genderType == 2) {
                    repo.config.session.searchGenderType = _armorSet.genderType;
                }else {
                    repo.config.session.searchGenderType = 1;
                    NSLog(@"invalid gender type %d", _armorSet.genderType);
                }
                if (_armorSet.hunterType >= 1 && _armorSet.hunterType <= 2) {
                    repo.config.session.searchHunterType = _armorSet.hunterType;
                }else {
                    repo.config.session.searchHunterType = 1;
                    NSLog(@"invalid hunter type %d", _armorSet.hunterType);
                }
                if (_armorSet.hunterRank >= 1 && _armorSet.hunterRank <= 6) {
                    repo.config.session.searchHunterRank = _armorSet.hunterRank;
                }else {
                    repo.config.session.searchHunterRank = 6;
                    NSLog(@"invalid hunter rank %d", _armorSet.hunterRank);
                }
                if (_armorSet.townRank >= 1 && _armorSet.townRank <= 5) {
                    repo.config.session.searchTownRank = _armorSet.townRank;
                }else {
                    repo.config.session.searchTownRank = 5;
                    NSLog(@"invalid townRank type %d", _armorSet.townRank);
                }
                if (_armorSet.weaponSlotCount >= -1 && _armorSet.weaponSlotCount <= 3) {
                    repo.config.session.searchWeaponSlotCount = _armorSet.weaponSlotCount;
                }else {
                    repo.config.session.searchWeaponSlotCount = 0;
                    NSLog(@"invalid weaponSlot count %d", _armorSet.weaponSlotCount);
                }
                
                PSTableController* table1 = [cont.childViewControllers objectAtIndex:0];
                PSTableController* table2 = [set.childViewControllers objectAtIndex:0];
                
                [table1 createDatas];
                [table2 createDatas];
           }else {
                UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"確認" message:@"マイセットに保存しますか" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
                [alert show];
            }
        }
            break;
        case BUTTON_TEXT: 
        {
            NSMutableString* txtArmor = [[NSMutableString alloc]init];
            NSMutableString* txtCharm = [[NSMutableString alloc]init];
            NSMutableString* txtMaterians = [[NSMutableString alloc]init];
            [_armorSet printArmorSetDetail:txtArmor :txtCharm : txtMaterians: FALSE];
            
            NSMutableString* text = [[NSMutableString alloc]init];

            [text appendString:txtArmor];
            [text appendString:txtCharm];

            TableControllerForText* nextView = [[TableControllerForText alloc]initWithText:text];
            [self.navigationController pushViewController:nextView animated:YES];
            
            [txtArmor release];
            [txtCharm release];
            [txtMaterians release];
        }
        break;
    }
}

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

-(void)callBackLoad1:(PSTableModel *)model {
    [_listSlot release];
    _listSlot = [[NSMutableArray alloc]init];
    
    PSTableSection* section;
    NSString* str;
    PSTableElement* elem;
    
    [model getSection:@"スキル" :TRUE];
    [model getSection:@"防具" :TRUE];

    PSArmorSet* set = _armorSet;

    section = [model getSection:@"防具" :TRUE];

    for (int i = 0; i < _armorSet.listArmor.count; ++ i) {
        PSTableElement* elem = [[PSTableElement alloc]init];
        NSMutableString* text = [[NSMutableString alloc]init];
        PSWrap* wrap = [_armorSet.listArmor objectAtIndex:i];
        [text appendFormat: @"%@【%d】", wrap.item.name, wrap.item.slotCount];
        elem.text = text;
        elem.value = wrap;
        if (wrap.item.itemType == ITEM_TYPE_CHARM) {
            [text appendFormat: @"\nスキル%@", wrap.item.skills];
        }
        [section.listElements addObject:elem];
        [elem release];
        [text release];
    }

    section = [model getSection:@"情報" :TRUE];
    
    str = [[NSString alloc]initWithFormat:@"HR:%d 村:%d 防御 %d->%d", set.hunterRank, set.townRank, set.defInitial, set.defMax];
    elem = [[PSTableElement alloc]init];
    elem.text = str;
    elem.value = nil;
    [str release];
    [section.listElements addObject:elem];
    [elem release];

    str = [[NSString alloc]initWithFormat:@"武器スロ【%d】合計スロ【%d】", set.weaponSlotCount, set.totalSlotCount];
    elem = [[PSTableElement alloc]init];
    elem.text = str;
    elem.value = nil;
    [str release];
    [section.listElements addObject:elem];
    [elem release];

    int shellTotal = set.shellFire + set.shellWater + set.shellIce + set.shellThunder + set.shellDragon;
    str = [[NSString alloc]initWithFormat:@"火【%d】水【%d】氷【%d】雷【%d】\n竜【%d】計【%d】", set.shellFire, set.shellWater, set.shellIce, set.shellThunder, set.shellDragon, shellTotal];
    elem = [[PSTableElement alloc]init];
    elem.text = str;
    elem.value = nil;
    [str release];
    [section.listElements addObject:elem];
    [elem release];

    elem = [[PSTableElement alloc]init];
    
    section = [model getSection:@"スキル" : TRUE];

    if (_listTargetSkill.count == 0) {
        PSTableElement* elem = [[PSTableElement alloc]init];
        elem.text = @"なし";
        elem.value = nil;
        [section.listElements addObject:elem]; 
        [elem release];
    }else {
        for (int i = 0; i < _listTargetSkill.count; ++ i) {
            PSTableElement* elem = [[PSTableElement alloc]init];
            NSString* str = [_listTargetSkill objectAtIndex: i];
            elem.text = str;
            elem.value = nil;
            [section.listElements addObject:elem];
            [elem release];
        }
    }   
}

-(void)callBackLoad2Async:(PSTableModel *)model {
    DecorationMatcher* matcher = nil;
    PSTableSection* section = nil;
    NSMutableArray *listSlotTmp = [[NSMutableArray alloc]init];
    
    PSSession* session = [[PSSession alloc]init];
    session.searchHunterType = _armorSet.hunterType;
    session.searchGenderType = _armorSet.genderType;
    session.searchHunterRank = _armorSet.hunterRank;
    session.searchTownRank = _armorSet.townRank;
    session.searchSkills = _armorSet.targetSkills;

    matcher = [[DecorationMatcher alloc]initWithData:session];

    [session release];
    
    [matcher canHaveEnoughDecoration:_armorSet :TRUE : listSlotTmp];
    [model validate];
    
    [_listSlot release];
    _listSlot = [[NSMutableArray alloc]init];
    for (int i = 0; i < listSlotTmp.count; ++ i) {
        DecorationSlot* slot = [listSlotTmp objectAtIndex:i];
        [slot updateAnotherSkill: _armorSet];
        [_listSlot addObject: slot];
    }

    [listSlotTmp release];
    listSlotTmp = nil;
    
    [model validate];
    if (_listSlot.count == 0) {
        PSTableElement* elem = [[PSTableElement alloc]init];
        elem.text = @"なにも見当たらないようです";
        elem.flgNextView = FLG_NEXT_NONE;
        elem.value = nil;
        
        NSString* str = [[NSString alloc]initWithFormat:@"装飾品"];
        section = [model getSection:str : TRUE];
        [str release];
        [section.listElements addObject:elem];
        [elem release];
    }else {
        for (int i = 0; i < _listSlot.count; ++ i) {
            NSString* str = [[NSString alloc]initWithFormat:@"装飾品【%d】", i+1];
            section = [model getSection:str : TRUE];
            [str release];
            
            DecorationSlot *slot = [_listSlot objectAtIndex: i];
            
            if (slot.realLength == 0) {
                PSTableElement *elem = [[PSTableElement alloc]init];
                elem.value = nil;
                elem.flgNextView = FLG_NEXT_NONE;
                elem.text = @"装飾品なし";
                [section.listElements addObject: elem];
                [elem release];
            }else {
                [model validate];
                for (int j = 0; j < slot.realLength; ++ j) {
                    PSWrap* deco = [slot realDecorationAt: j];
                    int count = [slot realCountAt: j];
                    BOOL isBodyCopy = [slot realBodyCopyAt: j];
                    
                    if (deco != nil && count > 0) {
                        if (isBodyCopy) {
                            NSMutableString* text = [[NSMutableString alloc]init];
                            [text appendString:@"胴【"];
                            [deco.item getArmorNameAndSlot:text];
                            [text appendFormat:@"×%d】", count];
                            
                            PSTableElement* elem = [[PSTableElement alloc]init];
                            elem.value = deco;
                            elem.text = text;
                            elem.flgNextView = FLG_NEXT_ITEM;
                            [section.listElements addObject:elem];
                            
                            [elem release];
                            [text release];
                        }else {
                            NSMutableString* text = [[NSMutableString alloc]init];
                            [deco.item getArmorNameAndSlot:text];
                            [text appendFormat:@"×%d", count];
                            
                            PSTableElement* elem = [[PSTableElement alloc]init];
                            elem.value = deco;
                            elem.text = text;
                            elem.flgNextView = FLG_NEXT_ITEM;
                            [section.listElements addObject:elem];
                            
                            [elem release];
                            [text release];
                        }
                        [model validate];
                    }
                }
            }
            [model validate];
            if (slot.hasAnotherSkill) {
                SkillSet* skills = slot.anotherSkill;
                for (int i = 0; i < skills.count; ++ i) {
                    SkillKind* kind = [skills.listKind objectAtIndex:i];
                    int point = skills.point[i];
                    BOOL range = skills.positive[i];
                    
                    SkillPoint *p = [[SkillPoint alloc]init];
                    p.skillKind = kind;
                    p.skillPoint = point;
                    p.positiveRange = range;
                    
                    Repository* repo = [Repository mainRepository];
                    SkillDB* skillDB = repo.skillDB;
                    
                    SkillPoint *name = [skillDB getNearSkillPoint: p];
                    
                    NSMutableString* text = [[NSMutableString alloc]init];
                    [text appendFormat: @"追加[%@]", name.pointName];
                    
                    PSTableElement* elem = [[PSTableElement alloc]init];
                    elem.value = nil;
                    elem.text = text;
                    
                    [section.listElements addObject: elem];
                    [text release];
                    [elem release];
                    [p release];
                    [model validate];
                }
            }
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PSTableSection* sect = [self.model getSectionAtIndex: indexPath.section];
    PSTableElement* elem = [sect.listElements objectAtIndex:indexPath.row];
    id obj = elem.value;
    
    if ([sect.title isEqual: @"防具"]) {
        PSWrap* wrap = obj;
        TableControllerForText* nextView = [[TableControllerForText alloc]initWithItem: wrap];
        [self.navigationController pushViewController:nextView animated:YES];
    }else if ([sect.title hasPrefix: @"装飾品"]) {
        PSWrap* wrap = obj;
        TableControllerForText* nextView = [[TableControllerForText alloc]initWithItem:wrap];
        [self.navigationController pushViewController:nextView animated:YES];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != 0) {
        Repository* repo = [Repository mainRepository];
        PSMySet* myset = repo.myset;
        [myset.listArmorSet addObject: _armorSet];
        [myset writeProperties];
    }
}

@end
