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

#import "TableControllerForTarget.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_CHECK_VISIBLE @"VISIBLE"
#define LONGACTION_UNCHECK_VISIBLE @"UNCHECK-VISIBLE"
#define LONGACTION_ALL @"ALL"
#define LONGACTION_PARTS @"PARTS"
#define LONGACTION_INFORMATION @"INFORMATION"
#define LONGACTION_CANCEL @"CANCEL"

@implementation TableControllerForTarget

@synthesize actionSheetData = _actionSheetData;
@synthesize actionSheetPath = _actionSheetPath;
@synthesize actionSheetText = _actionSheetText;
@synthesize settingDefine = _settingDefine;
@synthesize baseModel = _baseModel;
@synthesize viewModel = _viewModel;

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

-(id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) {
        self.navigationItem.title = @"対象防具";
        _baseModel = nil;
        [self doSearch: @""];
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

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

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

-(void)callBackLoad1:(PSTableModel *)model {
    _viewModel = model;
    
    [_baseModel release];
    _baseModel = [[PSTableModel alloc]init];    
    _baseModel.selectable = PS_SELECTABLE_PERSECTION;
    
    Repository* repository = [Repository mainRepository];
    PSBaseItems* baseItems = [repository items];
    
    PSTableSection* section0 = [_baseModel getSection:@"設定":TRUE];
    section0.selectable = PS_SELECTABLE_NONE;
    PSTableElement* elem0 = [[PSTableElement alloc]init];
    elem0.text = @"固定除外で検索する";
    elem0.cellStyle = PS_CELL_SWITCH;
    elem0.selected = PS_SELECTABLE_NONE;
    elem0.accessoryType = UITableViewCellAccessoryNone;
    Repository* repo = [Repository mainRepository];
    if (repo.config.session.searchWithUsableStatus) {
        elem0.valueOfInteger = 1;
    }else {
        elem0.valueOfInteger = 0;
    }
    [section0.listElements addObject:elem0];
    [elem0 release];
    
    for (int i = 0; i < 5; ++ i) {
        NSString* sectionName = nil;
        NSMutableArray* array = nil;
        switch(i) {
            case 0: 
                sectionName = @"頭防具";
                array = baseItems.listEquipHead;
                break;
            case 1: 
                sectionName = @"胴防具";
                array = baseItems.listEquipBody;
                break;
            case 2: 
                sectionName = @"腕防具";
                array = baseItems.listEquipArm;
                break;
            case 3: 
                sectionName = @"腰防具";
                array = baseItems.listEquipWeist;
                break;
            case 4: 
                sectionName = @"脚防具";
                array = baseItems.listEquipLeg;
                break;
        }
        
        if (array != nil) {
            Repository* repo = [Repository mainRepository];
            PSConfig* config = repo.config;
            for (int j = 0; j < array.count; ++ j) {
                PSItem* item = [array objectAtIndex:j];
                PSTableSection* section = [_baseModel getSection:sectionName :TRUE];
                section.selectable = PS_SELECTABLE_MULTI;
                if ([PSSession isExistForThisHunber:config.session: item]) {
                    PSTableElement* elem = [[PSTableElement alloc]init];
                    elem.text = item.name;
                    elem.value = item;
                    if (item.isCheckedForSearch) {
                        elem.selected = TRUE;
                    }

                    [section addElement: elem];
                }
            }
        }
    }
    [self doSearch:_actionSheetText];
}

- (void)viewDidLoad
{
    [super 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];
}

- (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* strCheckVisible = [[NSString alloc]initWithFormat:@"%@: 表示を全て選択", type];
        NSString* strUncheckVisible = [[NSString alloc]initWithFormat:@"%@: 表示を全て除外", type];
        NSString* strEverything = [[NSString alloc]initWithFormat:@"全選択（リセット）"];
        NSString* strParts = [[NSString alloc]initWithFormat:@"%@: のすべて", type];

        [_actionSheetData easyAddObject:nil: strOnlyone :LONGACTION_ONLY_ONE];
        [_actionSheetData easyAddObject:nil: strCheckVisible :LONGACTION_CHECK_VISIBLE];
        [_actionSheetData easyAddObject:nil: strUncheckVisible :LONGACTION_UNCHECK_VISIBLE];
        [_actionSheetData easyAddObject:nil: strParts :LONGACTION_PARTS];
        [_actionSheetData easyAddObject:nil: strEverything :LONGACTION_ALL];
        [_actionSheetData easyAddObject:nil: @"キャンセル" :LONGACTION_CANCEL];

        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:@"選択してください"
                                      delegate:self cancelButtonTitle:@"キャンセル"
                                      destructiveButtonTitle: nil 
                                      otherButtonTitles:strOnlyone, strCheckVisible, strUncheckVisible, strParts, strEverything, nil];

        [strOnlyone release];
        [strCheckVisible release];
        [strUncheckVisible release];
        [strEverything release];
        [strParts release];
        
        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.isCheckedForSearch = FALSE;
        }else {
            elem.selected = TRUE;
            item.isCheckedForSearch = TRUE;
        }
        
    }

    NSArray* reloadSelection = [NSArray arrayWithObjects: indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:reloadSelection withRowAnimation:UITableViewRowAnimationFade];
}

-(void)catchupValues {
    Repository* repo = [Repository mainRepository];
    PSTableModel* model = self.model;
    PSTableSection* sect = [model getSectionAtIndex:0];
    PSTableElement* elem = [sect.listElements objectAtIndex:0];
    if (elem.valueOfInteger != 0) {
        repo.config.session.searchWithUsableStatus = TRUE;
    }else {
        repo.config.session.searchWithUsableStatus = FALSE;
    }
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self doSearch:searchText];
}

-(void)doSearch:(NSString *)searchText
{
    if (searchText != _actionSheetText) {
        [_actionSheetText release];
        _actionSheetText = searchText;
        [searchText retain];
    }

    PSTableModel *source = _baseModel;
    PSTableModel *dest = [[PSTableModel alloc]init];
    dest.selectable = _baseModel.selectable;
    
    for(int i = 0; i < source.count; ++ i) {
        PSTableSection* sect = [source getSectionAtIndex:i];
        PSTableSection* destSec = [dest getSection: sect.title :TRUE];
        destSec.selectable = sect.selectable;
            
        for(int j = 0; j < sect.listElements.count; ++ j) {
            PSTableElement* elem = [sect.listElements objectAtIndex:j];

            PSItem* item = elem.value;
            NSString* name = elem.text;
            NSRange range = [name rangeOfString: _actionSheetText];
                
            if (_actionSheetText.length == 0 || range.location != NSNotFound) {
                PSTableElement* elem2 = elem;
                elem2.selected = item.isCheckedForSearch;
                [destSec.listElements addObject:elem2]; 
            }
        }
    }
    self.model = dest;
    [dest release];
    
    [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.isCheckedForSearch = TRUE;
                }
            }
        }else if ([strAction isEqual: LONGACTION_ONLY_ONE]) {
            BOOL found = FALSE;
            for(int i = 0; i < _baseModel.count; ++i ){
                PSTableSection* sect = [_baseModel getSectionAtIndex: i];
                if (i == _actionSheetPath.section) {
                    for(int j = 0; j < sect.listElements.count; ++ j){
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        if (item == selItem) {
                            item.isCheckedForSearch = TRUE;
                            NSLog(@"found %@", item.name);
                            found = TRUE;
                        }else { 
                            item.isCheckedForSearch = FALSE;
                        }
                    }
                }
            }
            NSLog(@"found = TRUE = %d FALSE = %d %d", TRUE, FALSE, found);
        }else if ([strAction isEqual: LONGACTION_CHECK_VISIBLE]) {
            /*for(int i = 0; i < _baseModel.count; ++i ){
             PSTableSection* sect = [_baseModel getSectionAtIndex:i];
             if (i == _actionSheetPath.section) {
             for(int j = 0; j < sect.listElements.count; ++ j){
             PSTableElement* elem = [sect.listElements objectAtIndex:j];
             PSItem* item = elem.value;
             item.isCheckedForSearch = FALSE;
             }
             }
             }*/
            for(int i = 0; i <  self.model.count; ++i ){
                PSTableSection* sect = [self.model getSectionAtIndex:i];
                if (i == _actionSheetPath.section) {
                    for(int j = 0; j < sect.listElements.count; ++ j){
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        item.isCheckedForSearch = TRUE;
                    }
                }
            }
        }else if ([strAction isEqual: LONGACTION_UNCHECK_VISIBLE]) {
            /*for(int i = 0; i < _baseModel.count; ++i ){
             PSTableSection* sect = [_baseModel getSectionAtIndex:i];
             if (i == _actionSheetPath.section) {
             for(int j = 0; j < sect.listElements.count; ++ j){
             PSTableElement* elem = [sect.listElements objectAtIndex:j];
             PSItem* item = elem.value;
             item.isCheckedForSearch = FALSE;
             }
             }
             }*/
            for(int i = 0; i <  self.model.count; ++i ){
                PSTableSection* sect = [self.model getSectionAtIndex:i];
                if (i == _actionSheetPath.section) {
                    for(int j = 0; j < sect.listElements.count; ++ j){
                        PSTableElement* elem = [sect.listElements objectAtIndex:j];
                        PSItem* item = elem.value;
                        item.isCheckedForSearch = FALSE;
                    }
                }
            }
        }
        
        [_actionSheetData release];
        [_actionSheetPath release];
        _actionSheetData = nil;
        _actionSheetPath = nil;
        
        if ([strAction isEqual: LONGACTION_CANCEL]
        || [strAction isEqual: LONGACTION_INFORMATION]) {
            //nothing
        }else {
            [self doSearch: _actionSheetText];
        }
    }
}



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

@end
