//
//  MWKeyedResult.m
//  avtams
//
//  Created by matthew on Sat Jun 05 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//

#import "MWKeyedResult.h"
#import "myResults.h"
#import "ctReadChar.h"
#import "tams.h"
#import "ctLimitCrit.h"
#import "TAMSCharEngine.h"
#import "coderec.h"
#import "NSRecordData.h"
#import "prefBoss.h"
#import "myProject.h"
#import "docDelegate.h"
#import "appDelegate.h"
#import "utils.h"
#import "tamsutils.h"
#import "MWPath.h"
#import "MWFakeFile.h"
#import "MGWPopUpButton.h"
//#import "AGRegex.h"
#import <stdio.h>
#import <stdlib.h>
#import "MWSortStackItem.h"
#import "stringCategories.h"
#import "MWTAMSStringCategories.h"
#define UPDATERECCOUNT	[self updateRecCount];

@implementation myResults (MWKeyedResult)
- (NSData *) keyedDataRepresentation
{
    NSMutableData *myDat = [[NSMutableData alloc] init];
    NSKeyedArchiver *rootArray = [[NSKeyedArchiver alloc] initForWritingWithMutableData: myDat];
    [rootArray setOutputFormat: NSPropertyListXMLFormat_v1_0];
    NSMutableData *dd;

    int ab;
    NSMutableArray *nameList, *fixedDataArray, *nKeys;
    NSMutableDictionary *nSets;
    dd = [[NSMutableData alloc] init];
    if(gWorkBench)
    {
        ab = [gWorkBench absPath];
    }
    else
        ab = ABSPATHMODE;
    //1. save the version
    [rootArray encodeObject: @"10" forKey: @"version"];
    
    FORALL(fileList)
    {
        if([temp hasFile] == NO)
        {
            NSWARNING(@"Cannot save in TAMS format until all source files have been saved.");
            return nil;
        }
    }
    ENDFORALL;
    
    //2. save the globals
    if([[myGlobals getGlobals] count])
        [rootArray encodeObject: [myGlobals getGlobals] forKey: @"globals"];
    //3. save the file list
    if([fileList count])
    {
        nameList = [[NSMutableArray alloc] init];
        FORALL(fileList)
        {
            [nameList addObject: [[(MWFile *) temp name] copy]];
        }
        ENDFORALL;
        [rootArray encodeObject: [nameList autorelease] forKey: @"fileList"];
    }
    //4. save the data
    if([backData count])
    {
        fixedDataArray = [[NSMutableArray alloc] init];
        FORALL(backData)
        {
            NSMutableDictionary *what;
            MWFile *myObj;
            
            what = [[NSMutableDictionary alloc] init];
            [what addEntriesFromDictionary: temp];
            myObj = [temp objectForKey: @"_doc"];
            [what setObject: [[myObj name] copy] forKey: @"_doc"];
            [fixedDataArray addObject: what];
        }
        ENDFORALL;
        [rootArray encodeObject: [fixedDataArray autorelease] forKey: @"backData"];
    }
    
    //5. save the visible data
    if([myData count])
        [rootArray encodeObject: [self arrayFromSubset: myData] forKey: @"frontData"];	
    
    //6. save the named sets
    
    nKeys = [namedSelDict allKeys];
    if([nKeys count])
    {
        nSets = [[NSMutableDictionary alloc] init];
        FORALL(nKeys)
        {
            [nSets setObject: [self arrayFromSubset: 
                [namedSelDict objectForKey: temp]] forKey: temp];
        }
        ENDFORALL;
        [rootArray encodeObject: [nSets autorelease] forKey: @"namedSets"];
    }
    //7. the limit string
    if(limitString)
        [rootArray encodeObject: limitString forKey: @"limit"];
    else
        [rootArray encodeObject: @"" forKey: @"limit"];
    //8. the list of columns
    if([colList count])
        [rootArray encodeObject: colList forKey: @"columns"];
    //9. the current string
    [rootArray encodeObject: [[[limitField stringValue] copy] autorelease] forKey: @"limitField"];
    //10. save the coder
    [rootArray encodeObject: [[codersString copy] autorelease] forKey: @"coders"];
    //11. save autosets
    if([autoSets count])
        [rootArray encodeObject: autoSets forKey: @"autosets"];
    //12. save the selected row
    [rootArray encodeObject: [NSNumber numberWithInt: [theResults selectedRow]] forKey: @"selectedRow"];
    //13. save marked list
    if([markedList count])
        [rootArray encodeObject: [self arrayFromSubset: markedList] forKey: @"marked"];
    //14. save summary reports
    if([summReports count])
        [rootArray encodeObject: summReports forKey: @"summaryReports"];
    //15. save date string
    [rootArray encodeObject: [[dfString copy] autorelease] forKey: @"dateFormat"];
    [rootArray encodeObject: [NSNumber numberWithInt: dfIndex] forKey: @"dateFormatIndex"];
    //16. save auto history
    if([autoHistory count])
        [rootArray encodeObject: autoHistory forKey: @"autohistory"];
    [rootArray encodeObject: [[autoHistoryStart copy] autorelease] forKey: @"autohistoryStart"];
    //17. save media dictionary
    if([mediaDict count])
        [rootArray encodeObject: [[mediaDict copy] autorelease] forKey: @"mediaDictionary"];
    [rootArray finishEncoding];
    return myDat;
}

#define IFSAVEDKEY(X) if((testObj = [rootArray decodeObjectForKey: X]) != nil)

-(void) loadKeyedData
{
    NSMutableArray *dataArray;
    NSMutableDictionary *theDict;
    NSArray *theSetNames, *fl;
    int selRow;
    NSDictionary *theSavedNS;
    id testObj;
    NSKeyedUnarchiver * rootArray;
    //NSMutableArray *fileList = [NSMutableArray array];
    NSString *tPath;
    
    int vers;
    rootArray = [[NSKeyedUnarchiver alloc] initForReadingWithData: mySavedData];
        
    tPath = [self fileName];
    vers = [[rootArray decodeObjectForKey: @"version"] intValue];
        //        BOOL apm;
    //        NSMutableString *wbPath = [[NSMutableString alloc] init];f
    selRow = 0;
    if(!gWorkBench)
    {
        NSWARNING(@"Cannot open file directly. Must open through a workbench/project");
        return;
    }
    
    
    //rootArray = [NSUnarchiver unarchiveObjectWithData: mySavedData];
    {
        
        
        //2. save the globals
        IFSAVEDKEY(@"globals")
            [myGlobals setGlobals: [rootArray decodeObjectForKey: @"globals"]];
        //need to load the flag values
        //3. save the file list; have to convert to absolute paths
        IFSAVEDKEY(@"fileList")
        {
            fl = [rootArray decodeObjectForKey: @"fileList"];
            FORALL(fl)
            {
                if(![gWorkBench fileForName: temp])
                {
                    NSString *msg1 = [NSString  stringWithFormat:@"Cannot continue. Missing source file \"%@\" for this result.", temp];
                    NSWARNING(msg1);
                    return;
                    
                }
                else
                    [fileList addObject: [gWorkBench fileForName: temp]];
            }
            ENDFORALL;
        }
        //4. save the data
        IFSAVEDKEY(@"backData")
        {
            dataArray = [rootArray decodeObjectForKey: @"backData"];
            FORALL(dataArray)
            {
                theDict = [[NSMutableDictionary alloc] initWithDictionary: temp];
                [theDict setObject: [gWorkBench fileForName: 
                    [temp objectForKey: @"_doc"]]
                            forKey:  @"_doc"];
                [backData addObject: theDict];
            }
            ENDFORALL;
        }
        //5. save the visible data
        IFSAVEDKEY(@"frontData")
            [myData addObjectsFromArray: [self subsetFromArray: [rootArray decodeObjectForKey: @"frontData"]]];	
        
        //6. save the named sets
        //get the dictionary
        IFSAVEDKEY(@"namedSets")
        {
            theSavedNS = [rootArray decodeObjectForKey: @"namedSets"];
            //get the keys
            theSetNames = [theSavedNS allKeys];
            //work through them
            FORALL(theSetNames)
            {
                [namedSelDict setObject: [self subsetFromArray: 
                    [theSavedNS objectForKey: temp]] forKey: temp];
            }
            ENDFORALL;
        }
        //if([theSetNames count]) [self renewNamedSelMenu];
        
        //7. get the limit string
        if(!limitString)
            limitString = [[NSMutableString alloc] init];
        IFSAVEDKEY(@"limit")
            [limitString setString: [rootArray decodeObjectForKey: @"limit"]];
        //8. get colList
        IFSAVEDKEY(@"columns")
            [colList addObjectsFromArray: [rootArray decodeObjectForKey: @"columns"]];
        //[myWindow setTitle: [[[self getMWFile] path] lastPathComponent]];
        //9.
        IFSAVEDKEY(@"limitField")
            [limitField setStringValue: [rootArray decodeObjectForKey: @"limitField"]];
        //10. get the Coder's list
        IFSAVEDKEY(@"coders")
            [codersString setString: [rootArray decodeObjectForKey: @"coders"]];
        //11. get the automatic sets
        IFSAVEDKEY(@"autosets")
        {
            {
                [autoSets addEntriesFromDictionary: [rootArray decodeObjectForKey: @"autosets"]];
            }
            [self rebuildAutoSetMenu];
        }
        //12. get the selected row
    
        {
            IFSAVEDKEY(@"selectedRow")
                selRow = [[rootArray decodeObjectForKey: @"selectedRow"] intValue];
            IFSAVEDKEY(@"marked")
                [self markBackArray: [rootArray decodeObjectForKey: @"marked"]];
        }
        //13. summary reports
        IFSAVEDKEY(@"summaryReports")
        {
            [summReports addEntriesFromDictionary: [rootArray decodeObjectForKey: @"summaryReports"]];
            [self rebuildSummReportMenu];
        }
        {
            IFSAVEDKEY(@"dateFormat")
                [dfString setString: [rootArray decodeObjectForKey: @"dateFormat"]];
            IFSAVEDKEY(@"dateFormatIndex")
                dfIndex = [[rootArray decodeObjectForKey: @"dateFormatIndex"] intValue];
        }
        IFSAVEDKEY(@"autohistory")
        {
            [autoHistory addObjectsFromArray: [rootArray decodeObjectForKey: @"autohistory"]];
        }
        IFSAVEDKEY(@"autohistoryStart")
        {
            [autoHistoryStart setString: [rootArray decodeObjectForKey: @"autohistoryStart"]];
        }
        IFSAVEDKEY(@"mediaDictionary")
        {
            [mediaDict addEntriesFromDictionary: [rootArray decodeObjectForKey: @"mediaDictionary"]];
        }
        
        [[NSNotificationCenter defaultCenter] addObserver: self 
                                                 selector: @selector(handleResultsDidChange:)
                                                     name: @"TAMSResultDidChange"
                                                   object: gWorkBench];
        
        FORALL(fileList)
        {
            [[NSNotificationCenter defaultCenter] addObserver: self 
                                                     selector: @selector(handleDirtySourceFlag:)
                                                         name: @"TAMSDocDidChange"
                                                       object: temp];
            
            [[NSNotificationCenter defaultCenter] addObserver: self 
                                                     selector: @selector(addCodeHandler:)
                                                         name: @"TAMSDocAddedCode"
                                                       object: temp];
            
            
            
        }ENDFORALL;
        
        [dirtySourceFlag setState: NSOnState];
        UPDATERECCOUNT;
        [self updateChangeCount: NSChangeCleared];
        [self rebuildSummReportMenu];
 	[self clearTable];
        [self setupTables];
       
        [theResults reloadData];
        if(selRow >= 0)
        {
            [theResults selectRow: selRow byExtendingSelection: NO];
            [theResults scrollRowToVisible: selRow];
        }
        
        [rootArray autorelease];
    }
}

@end
