//
//  XTBannerGridTextModel.m
//  XTads
//
//  Created by Rune Berg on 16/04/16.
//  Copyright © 2016 Rune Berg. All rights reserved.
//

#import "XTBannerGridTextModel.h"
#import "XTLogger.h"
#import "XTAllocDeallocCounter.h"


@interface XTBannerGridTextModel ()

@end


@implementation XTBannerGridTextModel

#define ROW_INITIAL_CAPACITY 100

OVERRIDE_ALLOC_FOR_COUNTER
OVERRIDE_DEALLOC_FOR_COUNTER

- (id)init
{
	self = [super init];
	if (self != nil) {
		_rowIndex = 0;
		_columnIndex = 0;
		_maxRowIndex = 0;
		_maxColumnIndex = 0;
		_rows = [NSMutableArray arrayWithCapacity:20];
	}
	return self;
}

- (void)clear
{
	self.rowIndex = 0;
	self.columnIndex = 0;
	self.maxRowIndex = 0;
	self.maxColumnIndex = 0;
	self.rows = [NSMutableArray arrayWithCapacity:20];
}

//TODO change arg type
- (void)setAttributedString:(NSAttributedString*)attrString
{
	//TODO try a simple approach:
	//			- consider sane limits for col/row
	
	NSString *string = attrString.string;
	if (attrString != nil) {
		NSUInteger len = string.length;
		for (NSUInteger i = 0; i < len; i++) {
			unichar ch = [string characterAtIndex:i];
			[self printCharInGrid:ch];
		}
	}
}

//----- internal -----

- (void)printCharInGrid:(unichar)ch
{
	if (ch == '\n') {
		
		// move to start of next line
		self.rowIndex += 1;
		self.columnIndex = 0;
		//TODO might have to actually add an empty line here - test in qtads
		
	} else {
		
		[self ensureRowWithIndex:self.rowIndex];
		[self ensureRowWithIndex:self.rowIndex hasColumnWithIndex:self.columnIndex];
		[self setChar:ch inRowWithIndex:self.rowIndex inColumnWithIndex:self.columnIndex];

		if (self.rowIndex > self.maxRowIndex) {
			self.maxRowIndex = self.rowIndex;
		}
		if (self.columnIndex > self.maxColumnIndex) {
			self.maxColumnIndex = self.columnIndex;
		}
		self.columnIndex += 1;
	}
}

- (void)ensureRowWithIndex:(NSUInteger)rowIndex
{
	NSInteger rowsToAdd = (rowIndex + 1 - self.rows.count);
	
	for (NSInteger i = rowsToAdd; i >= 1; i--) {
		[self.rows addObject:[NSMutableString stringWithCapacity:ROW_INITIAL_CAPACITY]];
	}
}

- (void)ensureRowWithIndex:(NSUInteger)rowIndex hasColumnWithIndex:(NSUInteger)columnIndex
{
	NSMutableString *row = self.rows[rowIndex];
	NSInteger colsToAdd = (columnIndex + 1 - row.length);
	
	for (NSInteger i = colsToAdd; i >= 1; i--) {
		[row appendString:@" "];
	}
}

- (void)setChar:(unichar)ch inRowWithIndex:(NSUInteger)rowIndex inColumnWithIndex:(NSUInteger)columnIndex
{
	NSMutableString *row = self.rows[rowIndex];
	NSRange range = NSMakeRange(columnIndex, 1);
	NSString *chStr = [NSString stringWithCharacters:&ch length:1];

	[row replaceCharactersInRange:range withString:chStr];
}

@end
