//
//  TableControllerBase.m
//  MHP3SkillSim
//

#import "PSTableController.h"
#import "CellBadge.h"
#import "NamedUISwitch.h"
#import "PSItem.h"
#import "PSTableModel.h"
#import "Repository.h"
#import "PSMutex.h"

@implementation PSTableController

@synthesize model = _model;
@synthesize rowLimit = _rowLimit;
#define _debug FALSE

-(id)init
{
    self = [super init];
    if (self) {
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) {
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(void)viewDidLoad {
    [self createDatas];
}

-(void)viewDidAppear:(BOOL)animated {
}

-(void)createDatas {
    @try {
        if (_model == nil) {
            [_model release];
        }
        _rowLimit = 100;
        _model = [[PSTableModel alloc]init];
        [self callBackLoad1: _model]; 
        [self cellValueChanged];
        [self performSelectorInBackground:@selector(createDatasAsync) withObject:nil];
    }
    @catch (NSException *exception) {
        NSLog(@"exception %@ %@", exception, [exception callStackSymbols]);
    }
}

-(void)createDatasAsync
{
    @try {
        PSTableModel* model2 = [[PSTableModel alloc]init];
        [self callBackLoad2Async:model2];
        [_model mergeSectionsFromTable: model2];
        [self performSelectorOnMainThread:@selector(createDatasEndOfAsync) withObject:nil waitUntilDone:FALSE];
    }
    @catch (NSException *exception) {
        NSLog(@"exception %@ %@", exception, [exception callStackSymbols]);
    }
}

-(void)createDatasEndOfAsync
{
    [self cellValueChanged];
}

-(void)callBackLoad1:(PSTableModel *)model {
/*    NSLog(@"you need override");
    [model easyAddObject:@"a" :@"aaa" : @"1"];
    [model easyAddObject:@"b" :@"bbb" : @"2"];
    [model easyAddObject:@"c" :@"ccc" : @"3"];
    return;*/
}

-(void)callBackLoad2Async:(PSTableModel *)model {
    
}

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_debug) NSLog(@"numberOfSectionsInTableView");
    return _model.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section < 0 || _model.count <= section) {
        if (_debug) NSLog(@"titleForHeaderInSection empty");
        return @"";
    }
    PSTableSection* sect = [_model getSectionAtIndex: section];
    return sect.title == nil ? @"" : sect.title;
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_debug) NSLog(@"numberOfRowsInSection");
    PSTableSection* sect = [_model getSectionAtIndex :section];
    int cnt = sect.listElements.count;
    if (cnt >= _rowLimit) {
        cnt = _rowLimit;
    }
    return cnt;
}

#pragma mark - Table view delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_debug) NSLog(@"cellForRowAtIndexPath");

    static UIImage* normalImage = nil;
    static UIImage* selectedImage = nil;

    @try {
        if (indexPath.row + 1 >= _rowLimit) {
            _rowLimit += 100;
            [self cellValueChanged];
        }
        
        Repository* repo = [Repository mainRepository];
        PSTableModel* model = _model;
        PSTableSection* sect = [model getSectionAtIndex: indexPath.section];
        PSTableElement* elem = [sect.listElements objectAtIndex:indexPath.row];
        
        if (elem.text == nil) {
            [self fillTextForElement:indexPath :elem];
        }
        
        NSString* cellID = nil;
        switch (elem.cellStyle) {
            case PS_CELL_NORMAL:
                cellID = @"pc-cell-normal";
                break;
            case PS_CELL_SWITCH:
                cellID = @"pc-cell-swith";
                break;
            case PS_CELL_SUMMARY:
                cellID = @"pc-cell-summary";
                break;
            case PS_CELL_BADGE:
                cellID = @"pc-cell-badge";
                break;
        }
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                          reuseIdentifier:cellID];
        }
        
        cell.textLabel.text = elem.text;
        //CGRect rect = cell.bounds;
        //int height2 = [PSTableController textHeight:elem.text];
        //CGRect rect2 = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, height2);
        //cell.bounds = rect2;
        
        UIView* subView1 = nil;
        
        if (normalImage == nil) {
            normalImage = [UIImage imageNamed: @"normal.png"];
            selectedImage = [UIImage imageNamed: @"selectedx1.png"];
            for (int i = 0; i < 100000; ++ i) {
                [normalImage retain];
                [selectedImage retain];
            }
        }
        
        if (elem.cellStyle == PS_CELL_SWITCH) {
            subView1 = [[NamedUISwitch alloc]initWithFrame:CGRectMake(200, 3, 100, 25)];
            ((NamedUISwitch*)subView1).indexPath = indexPath;
            [((NamedUISwitch*)subView1) addTarget:self action:@selector(toggleValue:)
                                 forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.imageView.image = nil;
        }
        else if (elem.cellStyle == PS_CELL_BADGE) {
            CellBadge *badge = [[CellBadge alloc] initWithFrame:CGRectMake(0, 0, 40, 25)];
            badge.value = elem.valueOfBadge;
            cell.accessoryView = badge;
            [badge release];
            cell.editingAccessoryType = UITableViewCellAccessoryCheckmark;
        }
        else if (elem.cellStyle == PS_CELL_SUMMARY) {
            UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(200, 3, 100, 25)];
            cell.accessoryView = label;
            label.text = elem.valueOfSummary;
        }
        int selectable = model.selectable;
        if (selectable == PS_SELECTABLE_PERSECTION) {
            selectable = sect.selectable;
        }
        if (selectable != PS_SELECTABLE_NONE) {
            cell.imageView.image = (elem.selected != FALSE) ? selectedImage :  normalImage; 
        }else {
            cell.imageView.image = nil;
        }
        if (elem.flgNextView) {
            //cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
            cell.accessoryType = UITableViewCellAccessoryNone;
        }else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        if (subView1 != nil) {
            for (int i = 0; i < cell.contentView.subviews.count; ++ i) {
                UIView* view = [cell.contentView.subviews objectAtIndex:i];
                if (view.tag == 12355) {
                    [view removeFromSuperview];
                    i = -1;
                }
            }
            subView1.tag = 12355;
            subView1.backgroundColor = ([indexPath row]%2)?repo.color1:repo.color2;
            cell.accessoryView.backgroundColor = ([indexPath row]%2)?repo.color1:repo.color2;
            [cell.contentView  addSubview: subView1];
            [subView1 release];
        }
        
        cell.textLabel.lineBreakMode = UILineBreakModeCharacterWrap;
        cell.textLabel.numberOfLines = 0;
        
        cell.detailTextLabel.lineBreakMode = UILineBreakModeCharacterWrap;
        cell.detailTextLabel.numberOfLines = 0;
        cell.textLabel.font = repo.userFont;
        
        if (elem.cellStyle == PS_CELL_NORMAL) {
            cell.textLabel.text = elem.text;
        }
        else if (elem.cellStyle == PS_CELL_BADGE) {
            cell.textLabel.text = elem.text;
            
            CellBadge* sw = (CellBadge*)subView1;
            sw.value = elem.valueOfBadge;
        }
        else if (elem.cellStyle == PS_CELL_SWITCH) {
            cell.textLabel.text = elem.text;
            
            NamedUISwitch* sw = (NamedUISwitch*)subView1;
            sw.indexPath = indexPath;
            [sw setOn: (elem.valueOfInteger > 0) ? YES : NO];
        }
        else if (elem.cellStyle == PS_CELL_SUMMARY) {
            cell.textLabel.text = elem.text;
            cell.detailTextLabel.text = elem.valueOfSummary; //TODO
        }

        return cell;
    }
    @catch (NSException *exception) {
        NSLog(@"exception %@ %@", exception, [exception callStackSymbols]);
    }
    return nil;
}

-(void)toggleValue:(id)sender;
{
    NamedUISwitch* sel = (NamedUISwitch*)sender;
    PSTableModel* model = self.model;
    PSTableSection* sect = [model getSectionAtIndex: sel.indexPath.section];
    PSTableElement* elem = [sect.listElements objectAtIndex: sel.indexPath.row];

    if (sel.on) {
        elem.valueOfInteger = 1;
    }else {
        elem.valueOfInteger = 0;
    }

    [self catchupValues];
    [self cellValueChanged];
}

-(void)catchupValues {
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    Repository* repo = [Repository mainRepository];
    cell.backgroundColor = ([indexPath row]%2)?repo.color1:repo.color2;
    cell.accessoryView.backgroundColor = cell.backgroundColor;

    NSArray* sub = cell.contentView.subviews;
    for (int i = 0; i < sub.count; ++ i) {
        UIView* view = [sub objectAtIndex:i];
        if (view.tag == 12355) {
            view.backgroundColor = cell.backgroundColor;
        }
    }
}

-(CGFloat)tableView:tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PSTableModel* model = [self model];
    if (model.count <= indexPath.section) {
        return 20;
    }
    PSTableSection* sect = [model getSectionAtIndex: indexPath.section];
    if (sect.listElements.count <= indexPath.row) {
        return 20;
    }
    PSTableElement* elem = [sect.listElements objectAtIndex:indexPath.row];
    
    if (elem.cellHeight != 0) {
        return elem.cellHeight;
    }

    if (elem.text == nil) {
        [self fillTextForElement:indexPath :elem];
    }    
    elem.cellHeight = [PSTableController textHeight:elem.text];    
    return elem.cellHeight;
}

-(void)cellValueChanged {
    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.cellHeight = 0;
        }
    }
    return [self.tableView reloadData];
}

static int textHeight0 = 0;

+(int)textHeight:(NSString*)str
{
    Repository* repo = [Repository mainRepository];

    if (textHeight0 == 0) {
        UILabel* label = [[UILabel alloc]init];
        label.font = repo.userFont;
        label.text = @"test";
        [label sizeToFit];
        CGRect rect = label.bounds;
        textHeight0 = rect.size.height;
        [label release];
    }
    
    if (str == nil) {
        NSException *exception = [[NSException alloc]initWithName:@"memoryerror" reason:@"nil" userInfo:nil];
        [exception raise];
    }

    int lines = 1;
    for (int i = 0; i < str.length - 1; ++ i) {
        int ch = [str characterAtIndex:i];
        if (ch == '\n') {
            lines ++;
        }
    }
    return textHeight0 * lines + 20;
}

- (void)fetchNext {
    _rowLimit += 100;
    [self.tableView reloadData];
}

-(void)fillTextForElement:(NSIndexPath*)index:(PSTableElement*)element {
    if (element.text != nil) {
        return;
    }
    element.text = @"test";
}

@end
