//
//  TableControllerForSkill.m
//  MHP3SkillSim
//

#import "TableControllerForSkill.h"
#import "PSTableModel.h"
#import "Repository.h"

@implementation TableControllerForSkill

@synthesize baseModel = _baseModel;
@synthesize actionSheetPath = _actionSheetPath;

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

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPress:)];
    [self.tableView addGestureRecognizer: press];
    press.delegate = self;
    [press release];

    self.navigationItem.title = @"スキル設定";

    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];

    _baseModel = self.model;
    [_baseModel retain];
    self.model = nil;
    [self doSearch: @""];
}

- (void)viewDidDisappear:(BOOL)animated
{
    SkillSet* skill = [[SkillSet alloc]init];
    for (int i = 0; i < self.baseModel.count; ++ i) {
        PSTableSection* sect = [self.baseModel getSectionAtIndex: i];
        for (int j = 0; j < sect.listElements.count; ++ j) {
            PSTableElement* elem = [sect.listElements objectAtIndex: j];
            if (elem.selected) {
                SkillPoint* point = elem.value;
                [skill set:point.skillKind :point.skillPoint :point.positiveRange];
            }
        }
    }

    Repository* repository = [Repository mainRepository];
    repository.config.session.searchSkills = skill;
    
	[super viewDidDisappear:animated];
}

-(void)callBackLoad1:(PSTableModel *)model {
    Repository* repository = [Repository mainRepository];
    SkillDB* skillDB = repository.skillDB;
    SkillSet* skills = repository.config.session.searchSkills;
    model.selectable = PS_SELECTABLE_MULTI;
        
    for (int i = 0; i < skillDB.countOfCategory; ++ i) {
        SkillCategory* category = [skillDB categoryOfIndex: i];
        
        for (int j = 0; j < category.count; ++ j) {
            SkillPoint* seek = [category pointAtIndex: j];

            PSTableElement* elem = [model easyAddObject:category.name :seek.pointName :seek];
            
            int x = [skills findByKind:seek.skillKind];
            
            if (x >= 0 && skills.point[x] == seek.skillPoint) {
                elem.selected = TRUE;
            }
        }
    }
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PSTableModel* model = self.model;
    PSTableSection* sect = [model getSectionAtIndex: indexPath.section];
    PSTableElement* elem = [sect.listElements objectAtIndex:indexPath.row];

    SkillPoint* sp = elem.value;
    BOOL oldSelected = elem.selected;

    if (oldSelected) {
        elem.selected = FALSE;
        NSArray* reloadSelection = [NSArray arrayWithObjects: indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadSelection withRowAnimation:UITableViewRowAnimationFade];
    }else {
        for (int i = 0; i < _baseModel.count; ++ i) {
            PSTableSection* sect2 = [_baseModel getSectionAtIndex: i];
            for (int j = 0; j < sect2.listElements.count; ++ j) {
                PSTableElement* elem2 = [sect2.listElements objectAtIndex:j];
                SkillPoint* seek = elem2.value;
                if (sp.skillKind == seek.skillKind) {
                    if (sp.skillPoint == seek.skillPoint) {
                        if (!elem2.selected) {
                            elem2.selected = TRUE;
                        }
                    }else {
                        if (elem2.selected) {
                            elem2.selected = FALSE;
                        }
                    }
                }
            }
        }
        NSMutableArray* reloadSelection = [[NSMutableArray alloc]init];
        for (int i = 0; i < model.count; ++ i) {
            PSTableSection* sect2 = [model getSectionAtIndex: i];
            for (int j = 0; j < sect2.listElements.count; ++ j) {
                PSTableElement* elem2 = [sect2.listElements objectAtIndex:j];
                SkillPoint* seek = elem2.value;
                if (sp.skillKind == seek.skillKind) {
                    NSIndexPath* path = [NSIndexPath indexPathForRow:j inSection:i];
                    [reloadSelection addObject:path];
                }
            }
        }
        [self.tableView reloadRowsAtIndexPaths:reloadSelection withRowAnimation:UITableViewRowAnimationFade];
        [reloadSelection release];
    }
}

-(void)doSearch:(NSString *)searchText
{
    PSTableModel *source = _baseModel;
    PSTableModel *dest = [[PSTableModel alloc]init];
    dest.selectable = source.selectable;
    
    for(int i = 0; i < source.count; ++ i) {
        PSTableSection* sect = [source getSectionAtIndex: i]; 
        
        for(int j = 0; j < sect.listElements.count; ++ j) {
            PSTableElement* elem = [sect.listElements objectAtIndex: j];
            SkillPoint* obj = elem.value;
            NSString* name = elem.text;
            NSRange range = [name rangeOfString: searchText];
            
            if (range.location == NSNotFound) {
                SkillKind* kind = obj.skillKind;
                range = [kind.name rangeOfString: searchText];
            }
            
            if (searchText.length == 0 || range.location != NSNotFound) {
                PSTableSection* sect2 = [dest getSection:sect.title :TRUE];
                [sect2.listElements addObject:elem];
            }
        }
    }
    self.model = dest;

    [self cellValueChanged];
}

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

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

- (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;
        
        [_actionSheetPath release];
        _actionSheetPath = indexPath;
        [_actionSheetPath retain];
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:@"なにをしますか"
                                      delegate:self cancelButtonTitle:nil
                                      destructiveButtonTitle: nil 
                                      otherButtonTitles:nil];
        [actionSheet addButtonWithTitle:@"リセットする"];
        [actionSheet addButtonWithTitle:@"なにもしない"];
        
        actionSheet.destructiveButtonIndex = 0;
        actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1;
        
        //        actionSheet.actionSheetStyle = UIBarStyleBlackTranslucent;
        
        [actionSheet showInView:self.tableView.window];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        PSTableModel* model = [self model];
        for (int i = 0; i < model.count; ++ i) {
            PSTableSection* sect = [model getSectionAtIndex:i];
            for (int j = 0; j < sect.listElements.count; ++ j) {
                PSTableElement* elem = [sect.listElements objectAtIndex:j];
                elem.selected = FALSE;
            }
        }
        
        [self cellValueChanged];
    }
}

@end
