//
//  TableControllerForTarget.m
//  MHP3SkillSim
//

#import "TableControllerForViewFilter.h"
#import "Repository.h"
#import "PSITem.h"
#import "PSItemType.h"
#import "Repository.h"
#import "PSConfig.h"
#import "PSItemViewController.h"
#import "PSMutex.h"

#define LONGACTION_ONLY_ONE @"ONLY"
#define LONGACTION_ONLY_VISIBLE @"VISIBLE"
#define LONGACTION_ONLY_NO_VISIBLE @"NOVISIBLE"
#define LONGACTION_ALL @"ALL"
#define LONGACTION_PARTS @"PARTS"
#define LONGACTION_INFORMATION @"INFORMATION"
#define LONGACTION_CANCEL @"CANCEL"

@implementation TableControllerForViewFilter

@synthesize actionSheetData = _actionSheetData;
@synthesize actionSheetPath = _actionSheetPath;
@synthesize actionSheetText = _actionSheetText;
@synthesize settingDefine = _settingDefine;
@synthesize listResultSearch = _listResultSearch;
@synthesize listResultChecked = _listResultChecked;
@synthesize baseModel = _baseModel;

-(id)initWithList:(NSMutableArray *)listResultSearch {
    self = [self init];
    if (self) {
        _listResultSearch = listResultSearch;
        [_listResultSearch retain];
    }
    return self;
}

-(id)init {
    return [self initWithStyle: UITableViewStyleGrouped];
}

-(id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) {
        self.navigationItem.title = @"対象防具";
        [PSItem clearEveryViewFound];
        for (int i = 0; i < _listResultSearch.count; ++ i) {
            PSArmorSet* set = [_listResultSearch objectAtIndex: i];
            PSWrap* charm = [set.listArmor objectAtIndex:5];
            charm.item.viewFound = FALSE;
        }
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(void)dealloc
{
    [_actionSheetPath release];
    [_actionSheetData release];
    [_actionSheetText release];
    [_settingDefine release];
    [_listResultSearch release];
    [super dealloc];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
    [self cellValueChanged];
}

-(void)callBackLoad1:(PSTableModel *)model {
    [self doSearch:model:_actionSheetText];
    [self cellValueChanged];
}

- (void)viewDidLoad
{
    UISearchBar* search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 400, 30)];
    search.showsCancelButton = YES;
    //search.showsSearchResultsButton = YES;
    search.delegate = self;
    
    //self.navigationItem.prompt = @"除外設定";
    self.navigationItem.titleView = search;
    [search release];
    
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPress:)];
    [self.tableView addGestureRecognizer: press];
    press.delegate = self;
    [press release];

    [self createDatas];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    PSTableModel* data = self.model;
    PSTableSection* sect = [data getSectionAtIndex: indexPath.section];
    PSTableElement* elem = [sect.listElements objectAtIndex:indexPath.row];
    PSItem* item = elem.value;
    
    PSItemViewController* nextView = [PSItemViewController alloc];
    [nextView initWithItem:item];
    
    UIBarButtonItem *backBarButtonItem = 
    [[UIBarButtonItem alloc] initWithTitle:@"戻る"
                                     style:UIBarButtonItemStyleBordered
                                    target:nil 
                                    action:nil];
    [self.navigationItem setBackBarButtonItem:backBarButtonItem];
    [backBarButtonItem release];        
    [self.navigationController pushViewController:nextView animated:YES];
    [nextView release];
    return;
}

- (void)didLongPress:(UILongPressGestureRecognizer *)sender
{
    CGPoint point;
    NSIndexPath *indexPath;
    
    if (sender.state == UIGestureRecognizerStateBegan) {        
        point = [sender locationInView:self.tableView];
        
        //[self resignFirstResponder];
        
        indexPath = [self.tableView indexPathForRowAtPoint:point];
        
        PSTableModel* data = self.model;
        PSTableSection* sect = [data getSectionAtIndex: indexPath.section];
        PSTableElement* elem = [sect.listElements objectAtIndex:indexPath.row];
        PSItem* item = elem.value;
        NSString* name = elem.text;
        
        [_actionSheetData release];
        [_actionSheetPath release];
        _actionSheetData = [[PSTableModel alloc]init];
        [_actionSheetData retain];
        
        _actionSheetPath = indexPath;
        [_actionSheetPath retain];
        
        NSString* type = [PSItemType itemTypeText: item.itemType];
        
        NSString* strOnlyone = [[NSString alloc]initWithFormat:@"%@: %@のみ", type, name];
        NSString* strVisibleCheck = [[NSString alloc]initWithFormat:@"%@: 表示を全て選択", type];
        NSString* strVisibleUncheck = [[NSString alloc]initWithFormat:@"%@: 表示を全て除外する", type];
        NSString* strParts = [[NSString alloc]initWithFormat:@"%@: のすべて", type];
        NSString* strEverything = [[NSString alloc]initWithFormat:@"全選択（リセット）"];
        
        [_actionSheetData easyAddObject:nil: strOnlyone :LONGACTION_ONLY_ONE];
        [_actionSheetData easyAddObject:nil: strVisibleCheck :LONGACTION_ONLY_VISIBLE];
        [_actionSheetData easyAddObject:nil: strVisibleUncheck :LONGACTION_ONLY_NO_VISIBLE];
        //[_actionSheetData easyAddObject:nil: strParts :LONGACTION_PARTS];
        [_actionSheetData easyAddObject:nil: strEverything :LONGACTION_ALL];
        [_actionSheetData easyAddObject:nil: @"キャンセル" :LONGACTION_CANCEL];
        
        [strOnlyone release];
        [strVisibleCheck release];
        [strVisibleUncheck release];
        [strEverything release];
        [strParts release];
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:@"選択してください"
                                      delegate:self cancelButtonTitle:@"キャンセル"
                                      destructiveButtonTitle: nil 
                                      otherButtonTitles:strOnlyone, strVisibleCheck, strVisibleUncheck, strEverything, nil];
        
        actionSheet.destructiveButtonIndex = 0;
        actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1;
        
        //        actionSheet.actionSheetStyle = UIBarStyleBlackTranslucent;
        
        [actionSheet showInView:self.tableView.window];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PSTableModel* model = self.model;
    PSTableSection* sect = [model getSectionAtIndex: indexPath.section];
    PSTableElement* elem = [sect.listElements objectAtIndex: indexPath.row];
    
    int seletable = model.selectable;
    if (seletable == PS_SELECTABLE_PERSECTION) {
        seletable = sect.selectable;
    }
    
    if (seletable == PS_SELECTABLE_NONE) {
        return;
    }
    
    BOOL oldSelected = elem.selected;
    
    PSItem* item = elem.value;
    if (item != nil) {
        if (oldSelected) {
            elem.selected = FALSE;
            item.isCheckedForView = FALSE;
        }else {
            elem.selected = TRUE;
            item.isCheckedForView = TRUE;
        }
    }
    
    [self createDatas];
}

-(void)catchupValues {
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    PSTableModel *model = [[PSTableModel alloc]init];
    [self doSearch:model:searchText];
    self.model = model;
    [model release];
    [self cellValueChanged];
}

-(void)doSearch:(PSTableModel*)model:(NSString *)searchText
{
    if (searchText != _actionSheetText) {
        [_actionSheetText release];
        _actionSheetText = searchText;
        [searchText retain];
    }
    
    //badgeの数値をリセットする
    [PSItem clearEveryViewCount];
    [PSItem clearEveryViewFound];
    for (int i = 0; i < _listResultSearch.count; ++ i) {
        PSArmorSet* set = [_listResultSearch objectAtIndex: i];
        PSWrap* charm = [set.listArmor objectAtIndex:5];
        charm.item.viewCount = 0;
        charm.item.viewFound = FALSE;
    }

    //結果リストからViewFoundを更新する
    //checkを反映した結果リストをつくる
    NSMutableArray* tempResult = [[NSMutableArray alloc]init];
    for (int i = 0; i < _listResultSearch.count; ++ i) {
        PSArmorSet* set = [_listResultSearch objectAtIndex:i];
        BOOL dis = FALSE;
        for (int j = 0; j < set.listArmor.count; ++ j) {
            PSWrap* wrap = [set.listArmor objectAtIndex:j];
            PSItem* item = wrap.item;
            item.viewFound = TRUE;
            if (item.isCheckedForView == FALSE) {
                dis = TRUE;
            }
        }
        if (dis) {
            continue;
        }
        for (int j = 0; j < set.listArmor.count; ++ j) {
            PSWrap* wrap = [set.listArmor objectAtIndex:j];
            PSItem* item = wrap.item;
            item.viewCount ++; //OK
        }
        [tempResult addObject:set];
    }
    [_listResultChecked release];
    _listResultChecked = tempResult;
    
    //モデルを作成する
    [_baseModel release];
    _baseModel = [[PSTableModel alloc]init];
    NSMutableSet* already = [[NSMutableSet alloc]init];

    for (int i = ITEM_TYPE_HEAD; i <= ITEM_TYPE_CHARM; ++ i) {
        PSTableSection* sect =  nil;
        NSString* str = nil;
        switch (i) {
            case ITEM_TYPE_HEAD:
                str = @"頭防具";
                break;
                
            case ITEM_TYPE_BODY:
                str = @"胴防具";
                break;

            case ITEM_TYPE_ARM:
                str = @"腕防具";
                break;

            case ITEM_TYPE_WEIST:
                str = @"腰防具";
                break;

            case ITEM_TYPE_LEG:
                str = @"足防具";
                break;
                
            case ITEM_TYPE_CHARM:
                str = @"お守り";
                break;
                
            default:
                abort();
                break;
        }
        sect = [_baseModel getSection:str :TRUE];
        NSMutableArray* ar0 = [[NSMutableArray alloc]init];
        for (int j = VIRTUAL_START; j <= VIRTUAL_END; ++ j) {
            PSItem* item = [PSItem getVirtualItem:i :j];
            [ar0 addObject:item];
        }
        Repository *repo = [Repository mainRepository];
        PSBaseItems* base = repo.items;
        [ar0 addObjectsFromArray:[base arrayByType:i]];
        for (int j = 0; j < ar0.count; ++ j) {
            PSItem* item = [ar0 objectAtIndex:j];
            if ([already containsObject:item]) {
                continue;
            }
            [already addObject: item];
            if (item.viewFound) {
                PSTableElement* elem = [[PSTableElement alloc]init];
                if (item.itemType == ITEM_TYPE_CHARM) {
                    NSMutableString* str = [[NSMutableString alloc]init];
                    [str appendFormat:@"%@[%d]%@", item.name, item.slotCount, item.skills];
                    elem.text = str;
                    [str release];
                }else {
                    elem.text = item.name;
                }
                elem.value = item;
                //item.viewCount ++; //NG
                [sect.listElements addObject:elem];
                [elem release];
            }
        }
        [ar0 release];
    }
    
    for (int i = 0; i < _listResultSearch.count; ++ i) {
        PSArmorSet* set = [_listResultSearch objectAtIndex: i];
        PSWrap* wrap = [set.listArmor objectAtIndex:5];
        if ([already containsObject: wrap.item]) {
            continue;
        }
        [already addObject:wrap.item];
        PSTableSection* sect = [_baseModel getSection:@"お守り" : TRUE];
        PSTableElement* elem = [[PSTableElement alloc]init];
        NSMutableString* str = [[NSMutableString alloc]init];
        PSItem* item = wrap.item;
        
        [str appendFormat:@"%@[%d]%@", item.name, item.slotCount, item.skills];
        elem.text = str;
        [str release];

        elem.value = item;
        [sect.listElements addObject:elem];
        [elem release];
    }
    
    //作成したモデルを文字列検索して別のモデルにする
    if (model == nil) {
        return;
    }
    for (int i = 0; i < _baseModel.count; ++ i) {
        PSTableSection* sect = [_baseModel getSectionAtIndex:i];
        PSTableSection* sect2 = [model getSection:sect.title :TRUE];

        for (int j = 0; j < sect.listElements.count; ++ j) {
            PSTableElement* elem = [sect.listElements objectAtIndex:j];
            PSItem* item = elem.value;

            elem.selected = item.isCheckedForView;
            elem.cellStyle = PS_CELL_BADGE;
            elem.valueOfBadge = item.viewCount;

            if (_actionSheetText == nil || _actionSheetText.length == 0) {
                [sect2 addElement:elem];
            }else {
                NSRange range = [item.name rangeOfString:_actionSheetText];
                
                if (range.location != NSNotFound) {
                    [sect2 addElement:elem];
                }
            }
        }
    }
    model.selectable = PS_SELECTABLE_MULTI;
    [self cellValueChanged];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [searchBar resignFirstResponder];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{    
    if (_actionSheetPath != nil) {
        PSTableElement* objAction = [_actionSheetData easyElementByIndex:0 :buttonIndex];
        NSString* strAction = objAction.value;

        PSTableModel* model = self.model;        
        PSTableElement* elemTarget = [model easyElementByIndex:_actionSheetPath.section :_actionSheetPath.row];
        PSItem* selItem = elemTarget.value;
        
        if ([strAction isEqual: LONGACTION_CANCEL]) {
            //nothing
        }else if ([strAction isEqual: LONGACTION_ALL]) {
            for(int i = 0; i < _baseModel.count; ++i ){
                PSTableSection* sect = [_baseModel getSectionAtIndex: i];
                for(int j = 0; j < sect.listElements.count; ++ j){
                    PSTableElement* elem = [sect.listElements objectAtIndex:j];
                    PSItem* item = elem.value;
                    item.isCheckedForView = TRUE;
                }
            }
        }else if ([strAction isEqual: LONGACTION_ONLY_ONE]) {
            for(int i = 0; i < _baseModel.count; ++i ){
                PSTableSection* sect = [_baseModel getSectionAtIndex: i];
                for(int j = 0; j < sect.listElements.count; ++ j){
                    PSTableElement* elem = [sect.listElements objectAtIndex:j];
                    if (i == _actionSheetPath.section) {
                        PSItem* item = elem.value;
                        if (item == selItem) {
                            item.isCheckedForView = TRUE;
                        }else { 
                            item.isCheckedForView = FALSE;
                        }
                    }
                }
            }
        }else if ([strAction isEqual: LONGACTION_ONLY_VISIBLE]) {
            /*for(int i = 0; i < _baseModel.count; ++i ){
                if (i == _actionSheetPath.section) {
                    PSTableSection* sect = [_baseModel getSectionAtIndex:i];
                    for(int j = 0; j < sect.listElements.count; ++ j){
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        item.isCheckedForView = FALSE;
                    }
                }
            }*/
            for(int i = 0; i <  self.model.count; ++i ){
                PSTableSection* sect = [self.model getSectionAtIndex:i];
                for(int j = 0; j < sect.listElements.count; ++ j){
                    if (i == _actionSheetPath.section) {
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        item.isCheckedForView = TRUE;
                    }
                }
            }
        }else if ([strAction isEqual: LONGACTION_ONLY_NO_VISIBLE]) {
            /*for(int i = 0; i < _baseModel.count; ++i ){
                if (i == _actionSheetPath.section) {
                    PSTableSection* sect = [_baseModel getSectionAtIndex:i];
                    for(int j = 0; j < sect.listElements.count; ++ j){
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        item.isCheckedForView = FALSE;
                    }
                }
            }*/
            for(int i = 0; i <  self.model.count; ++i ){
                PSTableSection* sect = [self.model getSectionAtIndex:i];
                for(int j = 0; j < sect.listElements.count; ++ j){
                    if (i == _actionSheetPath.section) {
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        item.isCheckedForView = FALSE;
                    }
                }
            }
        }
        
        [_actionSheetData release];
        [_actionSheetPath release];
        _actionSheetData = nil;
        _actionSheetPath = nil;
        
        if ([strAction isEqual: LONGACTION_CANCEL]
            || [strAction isEqual: LONGACTION_INFORMATION]) {
            //nothing
        }else {
            PSTableModel *model = [[PSTableModel alloc]init];
            [self doSearch:model:_actionSheetText];
            self.model = model;
            [model release];
            [self cellValueChanged];
        }
    }
}

-(void)actionSheetCancel:(UIActionSheet *)actionSheet{
    [_actionSheetData release];
    [_actionSheetPath release];
    _actionSheetData = nil;
    _actionSheetPath = nil;
}

-(void)doUpdateViewCount {
    [self catchupValues];
    if (_listResultSearch == nil) {
        NSLog(@"絞り込みもとの、listResutlSearchを設定してください。");
        return;
    }
    
    Repository* repo = [Repository mainRepository];
    PSBaseItems* items = repo.items;
    NSMutableArray* listArmor = nil;
    for(int itemType = ITEM_TYPE_HEAD; itemType < ITEM_TYPE_CHARM; ++ itemType) {
        switch (itemType) {
            case ITEM_TYPE_HEAD:
                listArmor = items.listEquipHead;
                break;
            case ITEM_TYPE_BODY:
                listArmor = items.listEquipBody;
                break;
            case ITEM_TYPE_ARM:
                listArmor = items.listEquipArm;
                break;
            case ITEM_TYPE_WEIST:
                listArmor = items.listEquipWeist;
                break;
            case ITEM_TYPE_LEG:
                listArmor = items.listEquipLeg;
                break;
            default:
                listArmor = nil;
                break;
        }
        if (listArmor != nil) {
            for (PSItem* e in listArmor) {
                e.viewCount = 0;
            }
        }
    }
    for (int i = VIRTUAL_START; i <= VIRTUAL_END; ++ i) {
        for (int slot = 0; slot <= 3; ++ slot) {
            PSWrap* p = [PSWrap getVirtualWrap:i :slot];
            p.item.viewCount = 0;
        }
    }

    NSMutableArray* listTemp = [[NSMutableArray alloc]init];
    
    for (int i = 0; i < _listResultSearch.count; ++ i) {
        PSArmorSet* set = [_listResultSearch objectAtIndex:i];
        BOOL filter = TRUE;
        for (int j = 0; j < set.listArmor.count; ++ j) {
            PSWrap* wrap = [set.listArmor objectAtIndex:j];
            if (!wrap.item.isCheckedForView) {
                filter = FALSE;
            }
        }
        if (filter) {
            [listTemp addObject: set];
        }
    }
    
    self.listResultChecked = listTemp;
    [listTemp release];

    PSTableModel* model = _baseModel;
    if (model == nil) {
        NSLog(@"model == nil");
        return;
    }
}

@end
