#import "summaryWatcher.h"
#import "MWSummaryReport.h"
#import "myResults.h"
#import "prefBoss.h"
#import "utils.h"
#import "MGWPopUpButton.h"
int sortGroupTranslateTable[5] = {2, 4, 3, 1, 5};
int groupSortTranslateTable[6] = {0,3,0,2,1,4};

@implementation summaryWatcher

-(id) init
{
    [super init];
    currGroups = [[NSMutableArray alloc] init];
    firstTimeFlag = 1;
    return self;
}

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

-(void) buildReportMenu
{
    NSArray *d;
    NSMutableArray *sd = [NSMutableArray array];
    [summReportPopMenu removeAllItems];
    d = [resultClass allSummReports];
    if([d count] == 0) return;
    [sd addObjectsFromArray: d];
    [sd sortUsingFunction: menuStringComp context: nil];
    [summReportPopMenu addItemsWithTitles: sd];

}
-(void) buildFieldMenu: (NSPopUpButton *) who
{
    NSArray *d;
    NSMutableArray *sd = [NSMutableArray array];
    NSMutableDictionary *dd;
    [who removeAllItems];
    d = [resultClass hotData];
    if([d count] == 0) return;
    dd = [d objectAtIndex: 0];
    [sd addObjectsFromArray: [dd allKeys]];
    [sd sortUsingFunction: menuStringComp context: nil];
    [who addItemsWithTitles: sd];
}

-(void) buildFieldMenus
{
    [self buildFieldMenu: summFieldPopMenu];
    [self buildFieldMenu: summSumFieldPopMenu];
    [self buildFieldMenu: summGroupPopMenu];
}
-(IBAction) addSortStackToGroups: (id) sender
{
    NSArray *ngrp;
    NSDictionary *lo;
    NSString *tt;
    
    ngrp = [self sortStack2Group];
    [currGroups addObjectsFromArray: ngrp];
    lo = [ngrp lastObject];
    [sortMenu selectItemAtIndex: 1];
    //tt = [lo objectForKey: @"field"];
    [summFieldPopMenu selectItemWithTitle: [lo objectForKey: @"field"]];
    [summFieldType selectItemWithTag: [[lo objectForKey: @"type"] intValue]];
    [summFieldCompLevel setIntValue: [[lo objectForKey: @"compLevel"] intValue]];
    [summGroupTable reloadData];
}
-(NSArray *) sortStack2Group
{
    NSMutableArray *grps;
    NSMutableDictionary *ssi;
    NSArray *sst;
    int i, n;
    grps = [NSMutableArray array];
    sst = [resultClass sortStackCopy];
    n = [sst count];
    for(i = 0; i < n; i++)
    {
        NSMutableDictionary *who;
        who = [sst objectAtIndex: i];
        
        ssi = [NSMutableDictionary dictionary];
        [ssi setObject: [[[who objectForKey: @"col"] copy] autorelease] forKey: @"field"];
        
        [ssi setObject: [NSNumber numberWithInt: groupSortTranslateTable[([[who objectForKey: @"type"] intValue]) ] ]forKey: @"type"];
        if([who objectForKey: @"codeLevel"] != nil)
            [ssi setObject: [[[who objectForKey: @"codeLevel"] copy] autorelease] forKey:@"compLevel" ];
        else
            [ssi setObject: [NSNumber numberWithInt: 0] forKey:@"compLevel" ];
        [grps addObject: ssi];
    }
    return grps;
}
-(NSArray *) group2SortStack
{
    NSMutableDictionary *ssi;
    NSMutableArray *sst;
    int i, n;
    sst = [NSMutableArray array];
    n = [currGroups count];
    for(i = 0; i < n; i++)
    {
        NSMutableDictionary *who;
        who = [currGroups objectAtIndex: i];
        
        ssi = [NSMutableDictionary dictionary];
        [ssi setObject: [[[who objectForKey: @"field"] copy] autorelease] forKey: @"col"];
        [ssi setObject: [[[resultClass dateFormat] copy] autorelease] forKey: @"dateFormat"];
        [ssi setObject: [NSNumber numberWithBool: YES] forKey: @"up"];
       // if(i > 0)
        //    [ssi setObject: [NSNumber numberWithInt: [[who objectForKey: @"type"] intValue] + 10] forKey: @"type"];
        //else
            
        [ssi setObject: [NSNumber numberWithInt: sortGroupTranslateTable[([[who objectForKey: @"type"] intValue]) ] ]forKey: @"type"];
        [ssi setObject: [[[who objectForKey: @"compLevel"] copy] autorelease] forKey: @"codeLevel"];
        [sst addObject: ssi];
    }
    return sst;
}

- (IBAction)addGroup:(id)sender
{
    NSMutableDictionary *newGrp;
    
    newGrp = [NSMutableDictionary dictionary];
    [newGrp setObject: [[[summGroupPopMenu titleOfSelectedItem] copy] autorelease] forKey: @"field"];
    [newGrp setObject: [NSNumber numberWithInt: [[summGroupTypePopMenu selectedItem] tag]] forKey: @"type"];
    if([[newGrp objectForKey: @"type"] intValue] == SRCODETYPE)
        [newGrp setObject: [NSNumber numberWithInt: [compLevelField intValue]] forKey: @"compLevel"];
    else
        [newGrp setObject: [NSNumber numberWithInt: 0] forKey: @"compLevel"];

    [currGroups addObject: newGrp];
    [summGroupTable reloadData];

}

- (IBAction)addSummRep:(id)sender
{

    if([[summName stringValue] isEqualToString: @""])
    {
        NSWARNING(@"You must provide a name");
        return;
    }
    if([resultClass isSummReport: [summName stringValue]] == YES)
    {
        NSString *q;
        q = [NSString stringWithFormat: @"Overwrite report named \"%@\"?", [summName stringValue]];
        if(NSYESNOQUESTION(q) == YES)
        {
            [resultClass delSummReport: [summName stringValue]];
        }
        else
            return;
    }
    [resultClass addSummReport: [summName stringValue] report: [self getCurrReport]
        global: (([projWideSwitch state] == NSOnState)? YES : NO)];
    [self buildReportMenu];
    [summReportPopMenu selectItemWithTitle: [summName stringValue]];
}

- (IBAction)cancelSumm:(id)sender
{
    [summPane orderOut: sender];
    [NSApp endSheet: summPane returnCode: 0];

}

- (IBAction)delAllGroup:(id)sender
{
    [currGroups removeAllObjects];
    [summGroupTable reloadData];
}

- (IBAction)delAllSummRep:(id)sender
{
    NSArray *a;
    
    if(NSYESNOQUESTION(@"Delete all data summary reports?") == NO) return;
    a = [resultClass allSummReports];
    FORALL(a)
    {
        [resultClass delSummReport: temp];
    }
    ENDFORALL;
    [self buildReportMenu];
}

- (IBAction)delGroup:(id)sender
{
    int r;
    r = [summGroupTable selectedRow];
    if(r >=0)
        [currGroups removeObjectAtIndex: r];
    [summGroupTable reloadData];
}

- (IBAction)delSummRep:(id)sender
{
    NSString *who, *q;
    who = [summReportPopMenu titleOfSelectedItem];
    q = [NSString stringWithFormat: @"Delete summary report: %@?",who];
    if(NSYESNOQUESTION(q) == NO) return;
    
    if([resultClass isSummReport: who])
    {
        [resultClass delSummReport: who];
        [self buildReportMenu];
    }
    
}

- (IBAction)loadReport:(id)sender
{
    NSDictionary *rep;
    NSString *t =  [summReportPopMenu titleOfSelectedItem];
    rep = [resultClass summReport:t];
    int n;
    [summName setStringValue: t];
    if(rep != nil)
    {
        [currGroups removeAllObjects];
        [currGroups addObjectsFromArray: [rep objectForKey: @"groupData"]];
        [summFieldPopMenu selectItemWithTitle: [rep objectForKey: @"summField"]];
        [countDupSwitch setIntValue: [[rep objectForKey: @"countDup"] intValue]];
        [summFieldCompLevel setIntValue: [[rep objectForKey: @"compLevel"] intValue]];
        [countDupSwitch setIntValue: [[rep objectForKey: @"countDup"] intValue]];
        [summTypePopMenu selectItemWithTagNumber: [rep objectForKey: @"summType"]];
        [summFieldType selectItem: [summFieldType itemAtIndex: [summFieldType indexOfItemWithTag:
            [[rep objectForKey: @"summFieldType"] intValue]]]];
        //[summFieldType selectItemWithTagNumber: [rep objectForKey: @"summFieldType"]];
        if([resultClass reportScope: t] == 2)
            [projWideSwitch setState: NSOnState];
        else
            [projWideSwitch setState: NSOffState];
        if([rep objectForKey: @"sort"] == nil)
            [sortMenu selectItemWithTag: 0];
        else
        {
            if([rep objectForKey: @"sortType"] == nil)
            {
                [sortMenu selectItemWithTag: 1];
            }
            else
            {
                n = [[rep objectForKey: @"sortType"] intValue];
                if(n >= 0 && n <= 2)
                    [sortMenu selectItemWithTag: n];
            }
        }
        [summGroupTable reloadData];
    }


}

- (IBAction)myAction:(id)sender
{
}

- (IBAction)okSumm:(id)sender
{
/*
    if([self validSetName: [namedSelField stringValue]] == NO)
    {
        NSWARNING(@"You must use a unique set name");
        return;
    }
*/
    [summPane orderOut: sender];
    [NSApp endSheet: summPane returnCode: 1];

}

- (IBAction)suffleDownGroup:(id)sender
{
    int r;
    int n = [currGroups count];
    r = [summGroupTable selectedRow];
    if(r < n - 1){
        [currGroups exchangeObjectAtIndex: r withObjectAtIndex:r + 1];
        [summGroupTable selectRow: r + 1 byExtendingSelection: NO];
    }

}

- (IBAction)suffleUpGroup:(id)sender
{
    int r;
    r = [summGroupTable selectedRow];
    if(r > 0){
        [currGroups exchangeObjectAtIndex:r withObjectAtIndex:r -1];
        [summGroupTable selectRow: r - 1 byExtendingSelection: NO];
    }


}

-(void) runSummReport: (NSDictionary *) r
{
    MWSummaryReport *myReport;
    /*
        myReport = [[MWSummaryReport alloc] init];
        [myReport setData: [resultClass hotData] andReport: r];
        [myReport setDateFormat: [resultClass dateFormat]];
        [NSBundle loadNibNamed: @"MWSummaryReport" owner: myReport];
        [myReport makeWindowControllers];
        [myReport windowControllerDidLoadNib: nil];
        [[myReport window] makeKeyAndOrderFront: self];
        [myReport buildSummary];
    */
    
        myReport = [[[MWSummaryReport alloc] init] autorelease];
        [myReport setData: [resultClass hotData] andReport: r];
        [myReport setDateFormat: [resultClass dateFormat]];
        [myReport makeWindowControllers];
        [[NSDocumentController sharedDocumentController] addDocument:myReport];
        [myReport showWindows];
       //[doc updateChangeCount:NSChangeDone];	// mark as dirty
        //[document showWindows];
        [[myReport window] makeKeyAndOrderFront: self];
        [myReport buildSummary];
}
-(NSMutableDictionary *) getCurrReport
{
        NSMutableDictionary *thisRep;
        thisRep = [NSMutableDictionary dictionary];
        [thisRep setObject: [[currGroups copy] autorelease] forKey: @"groupData"];
        [thisRep setObject: [[[summFieldPopMenu titleOfSelectedItem] copy] autorelease] forKey: @"summField"];
        [thisRep setObject: [NSNumber numberWithInt: [countDupSwitch intValue]] forKey: @"countDup"];
        [thisRep setObject: [NSNumber numberWithInt: [countBlanksSwitch intValue]] forKey: @"countBlank"];
        [thisRep setObject: [NSNumber numberWithInt: [summFieldCompLevel intValue]] forKey: @"compLevel"];
        [thisRep setObject: [NSNumber numberWithInt: [[summTypePopMenu selectedItem] tag]] forKey: @"summType"];
        [thisRep setObject: [NSNumber numberWithInt: [[summFieldType selectedItem] tag]] forKey: @"summFieldType"];
        [thisRep setObject: [NSNumber numberWithInt: [sortMenu tagOfSelectedItem]] forKey: @"sortType"];
        switch([sortMenu tagOfSelectedItem])
        {
            case 1:
            [thisRep setObject: [resultClass sortStackCopy] forKey: @"sort"];
                break;
            case 2:
                [thisRep setObject: [self group2SortStack] forKey: @"sort"];
                break;
        default:;
        };
        return thisRep;
}

-(void) summaryDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    
    if(returnCode)
    {
        id myReport;
        NSMutableDictionary *thisRep;
        thisRep = [self getCurrReport];
        [self runSummReport: thisRep];
   }

}
-(IBAction) resetFields: (id) sender
{
    [currGroups removeAllObjects];
    [summGroupTable reloadData];
    [self buildFieldMenus];
    [self buildReportMenu];
    [summName setStringValue: @""];
    [compLevelField setStringValue: @"0"];
    [summFieldCompLevel setStringValue: @"0"];
    [summFieldPopMenu selectItemAtIndex: 0];
    [summGroupPopMenu selectItemAtIndex: 0];
    [summGroupTypePopMenu selectItemAtIndex: 0];
    [summFieldType selectItemAtIndex: 0];
    [countDupSwitch setState: NSOnState];
    [summTypePopMenu selectItemAtIndex: 0];
    [countBlanksSwitch setState: NSOnState];
    [projWideSwitch setState: NSOffState];
    
    
}

-(void) doSummary
{
    NSWindow *who;
    if(firstTimeFlag)
    {
        [self resetFields: nil];
        firstTimeFlag = 0;
    }
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = resultWindow;
     [NSApp beginSheet: summPane
	modalForWindow: who
	modalDelegate: self
	didEndSelector: @selector(summaryDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    int n = [currGroups count];
    //NSLog(@"there are %d items in summ table\n", n);
    return n;
}
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    NSString *val = [[currGroups objectAtIndex: rowIndex] objectForKey: [aTableColumn identifier]];
    NSString *ident = [aTableColumn identifier];
    
    if([ident isEqualToString: @"type"] == YES)
    {
        int type = [[[currGroups objectAtIndex: rowIndex] objectForKey: @"type"] intValue];
        NSString *typeString;
        typeString =  [[summGroupTypePopMenu itemAtIndex: [summGroupTypePopMenu indexOfItemWithTag: type ]] title];
        if(type == SRCODETYPE)
        {
            return [NSString stringWithFormat: @"%@ (%d)", typeString, [[[currGroups objectAtIndex: rowIndex] objectForKey: @"compLevel"] intValue]];
        }
        else
            return typeString;
    }
    return val;
}

@end
