//
//  MWFakeDoc.m
//  avtams
//
//  Created by matthew on Thu Mar 18 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "MWRange.h"
#import "MWFakeDoc.h"
#import "stringCategories.h"
#import "TAMSCharEngine.h"
#import "prefBoss.h"

@implementation MWFakeDoc
-(id) initWithMWFile: (MWFile *) who
{
    [super init];
    myMWFile = who;
    isDirty = NO;
    openState = NO;
    theDoc = nil;
    return self;
}
-(MWFile *) myMWFile{return myMWFile;}
-(void) dealloc
{
    if(theDoc != nil) [theDoc release];
    [super dealloc];
}
-(id) initWithMWFile: (MWFile *) mw workBench: (myProject *) wb
{
    id it = [self init];
    gWorkBench = wb;
    myMWFile = mw;
    return it;
    
}
-(NSString *) getTitle
{
    return [myMWFile name];
}
-(NSString *) fileName
{
    return[myMWFile path];
}
-(NSString *) getData
{
    return [theDoc string];
}
-(void) updateCodeWindow {;}

-(void) setSelectedRange: (NSRange) r;
{
    selRange = r;
}
-(NSRange) selectedRange {return selRange;}
-(BOOL) isNew: (NSString *) who
{
    if(gWorkBench != nil) return [gWorkBench isMyCode: who];
    else return NO;
}
-(BOOL) isOpen{return openState;}
-(BOOL) open
{
    if(openState) return NO;
    theDoc = [[NSMutableAttributedString alloc] initWithAttributedString: [[self myMWFile] attributedString]];
    openState = YES;
    return YES;
}
-(void) setDirty{isDirty = YES;}
-(void) writeAndClose
{
    NSString *tp = [[self myMWFile] type];
    if([tp isEqualToString: @"rtf"] || [tp isEqualToString: @"RTF"])
    {
        [[theDoc RTFFromRange:NSMakeRange(0, [theDoc length]) documentAttributes: nil] 
            writeToFile: [[self myMWFile] path] atomically: YES];
    }
    else if([tp isEqualToString: @"rtfd"] || [tp isEqualToString: @"RTFD"])
    {
        [[theDoc RTFDFileWrapperFromRange:NSMakeRange(0, [theDoc length]) documentAttributes: nil] 
            writeToFile: [[self myMWFile] path] atomically: YES updateFilenames: YES];
    }
    else
    {
        [[theDoc string] writeToFile: [[self myMWFile] path] atomically: YES ];
    }
    
    openState = NO;
    [theDoc release];
    theDoc = nil;
}
-(void) setWorkBench: (id) who
{
    gWorkBench = who;
}
-(BOOL) isReal {return NO;}
-(MWFile *) getMyMWFile{ return myMWFile;}

-(void) adjustResultDocsAt: (int) loc forLength: (int) len
{
    NSMutableDictionary *msg;
    msg = [NSMutableDictionary dictionary];
    [msg setObject: [NSNumber numberWithInt: loc] forKey: @"location"];
    [msg setObject: [NSNumber numberWithInt: len] forKey: @"length"];
    [[NSNotificationCenter defaultCenter] postNotificationName: @"TAMSDocAddedCode"
                                                        object: [self getMyMWFile]
                                                      userInfo: msg
        ];
}
-(void) applyCode: (NSString *) aCode
{

    NSMutableAttributedString *theans, *theans1;
    NSRange where, newWhere, loc1, loc2;
    //int mc;
    int l1, l2, r1, r2;
    NSColor *myC;
    
    
    //mc = [gPrefBoss realColor];
    myC = [gWorkBench colorForCode: aCode];
    where = [self selectedRange];
    r1 = where.location;
    r2 = where.location + where.length;
    //[myUndo endUndoGroup];
    //[myUndo beginUndoGrouping];
    //[myTS beginEditing];
    theans = [[NSMutableAttributedString alloc] init];
    theans1 = [[NSMutableAttributedString alloc] init];
    [theans appendString: @"{"];
    [theans appendString: aCode];
    INSERTCODER(theans);
    [theans appendString:@"}"];
    //[self colorOn];
    
    [theans1 appendString: @"{/"];
    [theans1 appendString: aCode];
    INSERTCODER(theans1);
    [theans1 appendString: @"}"];
    [theans setColor: myC];
    [theans1 setColor: myC];
    loc1 = where;
    loc1.length = 0;
    
    
    [theDoc insertAttributedString: theans atIndex: loc1.location];
    l1 = loc1.length = [theans length];
    
    loc2.location = where.location + where.length + l1;
    loc2.length = 0;
    
     [theDoc insertAttributedString: theans1 atIndex: loc2.location];
    l2 = loc2.length = [theans1 length];
    newWhere = where;
    newWhere.length += l1 + l2;
    
    [self adjustResultDocsAt: r2 forLength: [theans1 length]];
    [self adjustResultDocsAt: r1 forLength: [theans length]];
    
     
    
    [theans release];
    [theans1 release];
    
}
-(void) recode: (NSString *) what first: (int) bwhere last: (int) ewhere from: (id) who withDef: (NSString *) myDef
{
    [self recode: what comment: nil first: bwhere last: ewhere from: who withDef: myDef];
}
-(void) recode: (NSString *) what comment:(NSString *) cmt first: (int) bwhere last: (int) ewhere from: (id) who withDef: (NSString *) myDef
{
    ctQChar *begChar, *endChar;
    int bTerminus, eTerminus;
    int bNew, eNew,  ll;
    int p1, p2, pr1, pr2, po1, po2;
    NSMutableAttributedString *ss;
    NSColor *myC;
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    
    ss = [[NSMutableAttributedString alloc] init];
    myC = [gWorkBench colorForCode: what];
    //set up the reader
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //get the first and end tags with the next characters
    //first:
    begChar = [[ctQChar alloc] init];
    [tc setCharLocation: (bwhere)];
    [tc readnext: begChar];
    bTerminus = [tc getCharLocation];
    
    //second
    endChar = [[ctQChar alloc] init];
    [tc setCharLocation: (ewhere)];
    [tc readnext: endChar];
    eTerminus = [tc getCharLocation];
    
    //make sure they're a match
    if([endChar tokentype] == ENDTOKEN && [begChar tokentype] == TOKEN &&
       [[endChar buff] isEqualToString: [begChar buff]] && [[endChar coder] isEqualToString: [begChar coder]])
    {
        
        //save the location
	//currSel = [theDoc selectedRange];
	
        //select the last
	//[theDoc setSelectedRange: NSMakeRange(ewhere, eTerminus - ewhere)];
        p2 = ewhere;
        pr2 = eTerminus - ewhere;
	//[self colorOn];
	[ss setString: @""];
	[ss appendString: @"{/"];
	[ss appendString: what];
	INSERTCODER(ss);
	if([[endChar extra] length] && cmt == nil)
	{
	    [ss appendString: @": "];
	    [ss appendString: [endChar extra]];
	}
	if(cmt != nil)
        {
	    [ss appendString: @": "];
	    [ss appendString: cmt];
	}
	[ss appendString: @"}"];
        //replace
        po2 = ll = [ss length];
	//[theDoc insertText: ss];
        [ss setColor: myC];
        [theDoc replaceCharactersInRange:  NSMakeRange(ewhere, eTerminus - ewhere) withAttributedString: ss];
        //[theDoc setSelectedRange: NSMakeRange(ewhere, ll)];
        //SETRAWCOLOR(myC);
	
        //get adjusted end and let the results know to adjust
        [tc clearSearchList];
        [tc addFileToSearchList: [self getMyMWFile]];
        [tc startSearch];
        [tc setCharLocation: (ewhere)];
        [tc readnext: endChar];
        eNew = [tc getCharLocation];
        //[who adjustBy: eNew - eTerminus startingAt: ewhere for: [self getMyMWFile]];
        
        [self adjustResultDocsAt: p2 + 1 forLength: po2 - pr2];
        //select the first
	//[theDoc setSelectedRange: NSMakeRange(bwhere, bTerminus - bwhere)];
        p1 = bwhere;
        pr1 = bTerminus - bwhere;
	//[self colorOn];
	[ss setString: @""];
	[ss appendString: @"{"];
	[ss appendString: what];
	INSERTCODER(ss);
	[ss appendString: @"}"];
        //replace
        po1 = ll = [ss length];
	//[theDoc insertText: ss];
        [ss setColor: myC];
        [theDoc replaceCharactersInRange:  NSMakeRange(bwhere, bTerminus - bwhere) withAttributedString: ss];
        //[theDoc setSelectedRange: NSMakeRange(bwhere, ll)];
        //SETRAWCOLOR(myC);
        //get adjusted beginning and let the results know to adjust
	[tc setCharLocation: (bwhere)];
	[tc readnext: (begChar)];
	bNew = [tc getCharLocation];
	//[who adjustBy: bNew - bTerminus startingAt: bwhere for: [self getMyMWFile]];
        [self adjustResultDocsAt: p1+1 forLength: po1 - pr1];
	//if it's new make sure to add it
        if([gWorkBench isMyCode: what]  && !myDef)
        {
            [gWorkBench addCode:  what definition: @""  active: YES append: YES];
            [gWorkBench broadcastCodeChange: NO];
            
        }
	else if([gWorkBench isMyCode: what])
	{
            [gWorkBench addCode:  what definition: myDef  active: YES append: YES];
            [gWorkBench broadcastCodeChange: NO];
            
	}
        else
        {
            if(!myDef)
            {
                if([myDef isEqualToString: @""] == NO)
                {
                    [gWorkBench addCode:  what definition: myDef  active: YES append: YES];
                    [gWorkBench broadcastCodeChange: NO];
                }
            }
            
        }
        
        //restore cursor
      }
    [self setDirty];
    [begChar release];
    [endChar release];
    [ss release];
    [tc release];
    
}
-(void) addCode: (NSString *) what from: (int) bwhere to: (int) ewhere from: (id) who withDef: (NSString *) myDef
{
    
    [self setSelectedRange: NSMakeRange(bwhere, ewhere - bwhere)];
    if([self isNew: what] || (![self isNew: what] && ((!myDef) ||[myDef isEqualToString: @""] == NO)) )
    {
        if(!myDef)  [gWorkBench addCode:  what definition: @""  active: YES append: YES];
	else if([myDef isEqualToString: @""] == YES) 
            [gWorkBench addCode:  what definition: @""  active: YES append: YES];
        else 
            [gWorkBench addCode:  what definition: myDef  active: YES append: YES];
        [gWorkBench broadcastCodeChange: NO];
        [self applyCode: what];
    }
    else [self applyCode: what];
        
    [self setDirty];
    
}
-(void) deleteCodeFromResultStartingWith: (int) bwhere endingWith: (int) ewhere from: (id) who
{
    ctQChar *begChar, *endChar;
    int bTerminus, eTerminus;
    int bNew;
    NSMutableAttributedString *ss;
    
    
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    
    ss = [[NSMutableAttributedString alloc] init];
    
    //set up the reader
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    //get the first and end tags with the next characters
    //first:
    begChar = [[ctQChar alloc] init];
    [tc setCharLocation: (bwhere)];
    [tc readnext: begChar];
    bTerminus = [tc getCharLocation];
    
    //second
    endChar = [[ctQChar alloc] init];
    [tc setCharLocation: (ewhere)];
    [tc readnext: endChar];
    eTerminus = [tc getCharLocation];
    
    //make sure they're a match
    if([endChar tokentype] == ENDTOKEN && [begChar tokentype] == TOKEN &&
       [[endChar buff] isEqualToString: [begChar buff]] && [[endChar coder] isEqualToString: [begChar coder]])
    {
        	
        //select the last
	//[theDoc setSelectedRange: NSMakeRange(ewhere, eTerminus - ewhere)];
	//[self colorOn];
	[ss setString: @""];
	//[theDoc insertText: ss];
        [theDoc replaceCharactersInRange:  NSMakeRange(ewhere, eTerminus - ewhere) withAttributedString: ss];
	
        //get adjusted end and let the results know to adjust
        //[who adjustBy: ewhere - eTerminus  startingAt: ewhere for: [self getMyMWFile]];
        [self adjustResultDocsAt: ewhere forLength: ewhere - eTerminus];
        //select the first
	//[theDoc setSelectedRange: NSMakeRange(bwhere, bTerminus - bwhere)];
	[ss setString: @""];
	//[theDoc insertText: ss];
        [theDoc replaceCharactersInRange: NSMakeRange(bwhere, bTerminus - bwhere) withAttributedString: ss];
        //get adjusted beginning and let the results know to adjust
	[tc setCharLocation: (bwhere)];
	[tc readnext: (begChar)];
	bNew = [tc getCharLocation];
	//[who adjustBy: bwhere - bTerminus startingAt: bwhere for: [self getMyMWFile]];
        [self adjustResultDocsAt: bwhere forLength: bwhere - bTerminus];
	//if it's new make sure to add it
        [gWorkBench broadcastCodeChange: NO];
        
        
        //restore cursor
    }
    [self setDirty];
    [begChar release];
    [endChar release];
    [ss release];
    [tc release];
    
}

-(void) ConvertMovieTimeToHHMMSS: (BOOL) hhmmssFormat
{
    long  l;
    NSString *ss;
    NSMutableArray *tLoc = [[NSMutableArray alloc] init];
    TAMSCharEngine *tc = [[TAMSCharEngine alloc] init];
    ctQChar *q;
    NSRange r,s;
    NSString *timeCode;
    int tt, i, n;
    BOOL timeMode, hfmt;
    double t1;
    NSString *theDocString;
    
    timeCode = [gPrefBoss getAVCode];
    if(!gWorkBench) return;
    [tc addFileToSearchList: [self getMyMWFile]];
    [tc startSearch];
    
    q = [[ctQChar alloc] init];
    
    timeMode = NO;
    r = NSMakeRange(0,0);
    while((tt = [tc scanNext: q]) != ENDOFFILE)
    {
        //scan through doc
        if(tt == TOKEN)
        {
            if([[q buff] isEqualToString: timeCode])
            {
                timeMode = YES;
            }
            else 
                timeMode = NO;
        }
        else if(timeMode == YES)
        {
            if(tt == CHAR)
            {
                hfmt = isHHMMSS([q buff]);
                if(hhmmssFormat)
                {
                    if(hfmt == NO) //this is one we want
                        [tLoc addObject: [[[MWRange alloc] initWithRange: [q range]] autorelease]];
                }
                else
                {
                    if(hfmt == YES)
                        [tLoc addObject: [[[MWRange alloc] initWithRange: [q range]] autorelease]];
                    
                }
                
            }
            timeMode = NO;
        }
        else timeMode = NO;                
    }
    [tc release];
    [q release];
    n = [tLoc count];
    theDocString = [theDoc string];
    for(i = n-1; i >= 0; i--)
    {
        NSString *newTime, *oldTime;
        MWRange *w;
        w = [tLoc objectAtIndex: i];
        oldTime = [theDocString substringWithRange: [w range]];
        if(hhmmssFormat)
            newTime = sec2hhmmss((unsigned) [oldTime doubleValue]);
        else
            newTime = [NSString stringWithFormat: @"%u", hhmmss2sec(oldTime)];
        [theDoc replaceCharactersInRange:  [w range] withAttributedString: [[[NSAttributedString alloc] initWithString: newTime] autorelease]];
        
    }
    [tLoc release];
}
@end
