#import "AcqDrawerQueryTableView.h"
#import "AcqQueryCell.h"
#import "DWUtil.h"


@implementation AqDrawerQueryTableView

/* Awake */

    - (void) awakeFromNib; {
        [super awakeFromNib];
        [self setRowHeight: 23];
        qc = [AqQueryController instance];
    }
    
            
#pragma mark -
/* Overrides */


    - (int) numberOfRows; {
        return [qc count];
    }
    
    - (int) numberOfColumns; {
        return 2;
    }
    
    - (void) addOrRemoveScroller; {
        id scrollView = [self enclosingScrollView];
        BOOL shouldHaveVerticalScroller = (_frame.size.height > [scrollView documentVisibleRect].size.height);
        if (shouldHaveVerticalScroller ^ [scrollView hasVerticalScroller]) {
            [scrollView setHasVerticalScroller: shouldHaveVerticalScroller];
            [[scrollView contentView] viewFrameChanged: nil];
        }
    }
    
    - (void) tile; {
        [super tile];
        [self addOrRemoveScroller];
    }


#pragma mark -
/* Draw override */
    
    - (void) drawRect: (NSRect) rect; 
    {
        int i, count;
        int dwColorIndex;

        float dy = _rowHeight + 2.0f;

        /* draw background */

            [white set];
            
            

        /* draw rows */
        
            i = floor(rect.origin.y/dy);
            count = MIN([self numberOfRows], ceil((rect.origin.y + rect.size.height)/dy));
            
            BOOL hasComputedFirstResponder = NO;
            BOOL isFirstResponder = NO;

            for (; i<count; i++) 
            {
                NSRect rowRect = [self rectOfRow: i];
                rowRect.size.height -= 0.5;

                rowRect.size.width = MIN(rowRect.size.width, rect.size.width+3);
                
                /* draw background, if necessary */
                if ( [self isRowSelected: i] ) {

                    if ( !hasComputedFirstResponder ) {

                        isFirstResponder = [[self window] firstResponder] == self && [[self window] isKeyWindow];
                        hasComputedFirstResponder = YES;

                    }

                    dwColorIndex = (isFirstResponder) ? kDWColorAlternateIndex : kDWColorSecondaryIndex;

                    [(isFirstResponder) ? alternate : secondary set];
                    NSRectFill(rowRect);

                } else {

                    dwColorIndex = kDWColorWhiteIndex;

                }
                
                /* draw the row */
                    
                    DWTableCell* cell = [qc cellAtIndex: i];
                    cell->dwColorIndex = dwColorIndex;
                    [cell drawWithFrame: rowRect inView: self];
            }
    }
    
@end