//
//  MatrixBuilder.m
//  ArmorP3V1
//
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MatrixBuilder.h"

@implementation MatrixBuilder

@synthesize listColumn = _listColumn;
@synthesize counter = _counter;
@synthesize skipCount = _skipCount;

-(id)init
{
    self = [super init];
    if (self) {
        _listColumn = [[NSMutableArray alloc]init];
        _counter = nil;
    }
    return self;
}

-(void)cleanup {
    [_listColumn removeAllObjects];
    free(_counter);
    _counter = nil;
}

-(void)dealloc
{
    if (_listColumn != nil) {
        [_listColumn release];
        _listColumn = nil;
    }
    if (_counter != nil) {
        free(_counter);
        _counter = nil;
    }
    [super dealloc];
}

-(void)addColumn:(NSArray*)column
{
    [_listColumn addObject: column];
}

-(long)iteratorCount
{
    long x = 1;
    for (int i = 0; i < _listColumn.count; ++i) {
        NSArray* e = [_listColumn objectAtIndex: i];
        x *= e.count == 0 ? 1 : e.count;
    }
    return x;
}

-(BOOL)hasNext
{
    for (int i = 0; i < _listColumn.count; ++i) {
        NSArray* e = [_listColumn objectAtIndex: i];
        if (_counter[i] >= e.count) {
            return NO;
        }
    }
    return YES;
}

-(void)start
{
    if (_counter != nil) {
        free(_counter);
    }
    _counter = calloc(sizeof(int), _listColumn.count);
}

-(BOOL)fetchNext:(NSMutableArray*)result
{
    if (![self hasNext]) {
        return NO;
    }
    for (int i = 0; i < _listColumn.count; ++i) {
        NSArray* e = (NSArray*)[_listColumn objectAtIndex: i];
        [result addObject: [e objectAtIndex: _counter[i]]];
    }
    [self increment];
    return YES;
}

-(BOOL)increment
{
    int x = 0;
    _counter[x]++;
    while (_counter[x] >= ((NSArray*)[_listColumn objectAtIndex: x]).count) {
        if (x + 1 >= _listColumn.count) {
            return NO;
        }
        _counter[x] = 0;
        x++;
        _counter[x]++;
    }
    return YES;
}

@end
