/*
 *  tamsutils.tamsCharSet
 *  TEST2
 *
 *  Created by matthew on Sat May 03 2003.
 *  Copyright (tamsCharSet) 2003 __MyCompanyName__. All rights reserved.
 *
 */

#include "tams.h"
#import "prefBoss.h"
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "tamsutils.h"

NSMutableCharacterSet *tamsCharSet=nil;
//#define DATASTRING(W,X) {[W appendBytes: [X cString] length: [X cStringLength]];}
//#define DATASTRING(W,X) {[W appendData: [X dataUsingEncoding: NSUnicodeStringEncoding allowLossyConversion: YES]];}

void DATASTRING(NSMutableData *W, NSString *X) 
{
    NSStringEncoding se, n;
    n = [gPrefBoss unicharValue];
    switch(n) {
        case 601: 
            se = NSUnicodeStringEncoding; 
            break;
        case 602:
            se = NSUTF8StringEncoding;
            break;
        case 603:
            se = NSNonLossyASCIIStringEncoding;
            break;
        case 604:
            se = NSISOLatin1StringEncoding;
            break;
        case 605:
            se = NSISOLatin2StringEncoding;
            break;
        case 606://this is the original form which does allow some foreign characters
            /* deprecated to 608 */
            [W appendBytes: [X cString] length: [X cStringLength]];
            return;
            break;
        case 607:
            se = NSNEXTSTEPStringEncoding;
            break;
        case 608:
            se = NSMacOSRomanStringEncoding;
            break;
        case 609:
            se = NSWindowsCP1252StringEncoding;
            break;

        default:
            se = NSMacOSRomanStringEncoding;
            break;
       };     
    [W appendData: [X dataUsingEncoding: se allowLossyConversion: YES]];
}

//#define DATACHAR(W,X) {unichar _ss[2]; _ss[0] = X; [W appendBytes: _ss length: 1];}
void DATACHAR(NSMutableData *W, unichar X)  {NSString *_ssss = [NSString stringWithFormat: @"%C",X]; DATASTRING(W,_ssss);}
void DATATAB(NSMutableData *W) {DATACHAR(W, '\t');}
void DATANL(NSMutableData *W) {DATACHAR(W, '\n');}

NSString *code2tag(NSString *mycode, BOOL open, BOOL result, NSString *comment)
{
    NSMutableString *ans = [NSMutableString string];
    
    if(open)
    {
        [ans appendString: [NSString stringWithFormat: @"{%@", mycode]];
    }
    else
    {
        [ans appendString: [NSString stringWithFormat: @"{/%@", mycode]];
    }
    
    if(result)
    {
        INSERTRESULTCODER(ans);
    }
    else
    {
        INSERTCODER(ans);
    }
    
    if(open == NO && comment != nil)
    {
        [ans appendString: [NSString stringWithFormat: @": %@}", comment]];
    }
    else
        [ans appendString: @"}"];
    
    return ans;
}

void makeTamsCharSet()
{
    NSCharacterSet *b;

    b= [NSCharacterSet characterSetWithCharactersInString: @">_"];
    tamsCharSet = [NSMutableCharacterSet alphanumericCharacterSet];
    [tamsCharSet formUnionWithCharacterSet: b];
    [tamsCharSet retain];
}
NSCharacterSet *tamsCharacterSet(void)
{
    if(!tamsCharSet)
        makeTamsCharSet();
    return tamsCharSet;
}
    
BOOL isCharLegal(unichar ch)
{
    
    if(!tamsCharSet)
        makeTamsCharSet();
        
    return [tamsCharSet characterIsMember: ch];

}

NSString *extractFirstCode(NSString *what)
{
    NSRange r;
    int i, n;
    
    n = [what length];
    if (n <= 0) return nil;
    r = NSMakeRange(NSNotFound,0);
    for(i = 0; i < n; i++)
    {
        if(isCharLegal([what characterAtIndex: i]))
        {
            if(r.location == NSNotFound)
            {
                r.location = i;
            }
            r.length++;
        }
        else
        {
            if(r.length > 0)
            {
                return [what substringWithRange: r];
            }
        }
    }
    if(r.length > 0)
    {
        return [what substringWithRange: r];
    }
    return nil;
}

BOOL isCodeNameLegal(NSString *who)
{

    NSCharacterSet  *ss;
    int i, n;

    if(!tamsCharSet)
        makeTamsCharSet();
//    ss = [NSCharacterSet characterSetWithCharactersInString: who];
//    return [tamsCharSet isSupersetOfSet: ss];
	n = [who length];

	for(i=0; i< n; i++)
	{
		if([tamsCharSet characterIsMember: [who characterAtIndex: i]] == NO)
			return NO;
	}
	return YES;

		
}

int codeLevel(NSString *code)
{
    int i, l, cnt;
    
    l = [code length];
    
    for(i = 0, cnt = 0; i < l; i++)
    {
        if([code characterAtIndex: i] == '>')
            cnt++;
    }
    
    return cnt + 1;

}
NSString *terminusOf(NSString *code)
{
    
    //make array of string
    NSMutableArray *arr = [NSMutableArray arrayWithArray: [code componentsSeparatedByString: @">"]];
    //return last element
    return [[[arr lastObject] copy] autorelease];
}

NSString *parentOf(NSString *code)
{
    
    //make array of string
    NSMutableArray *arr = [NSMutableArray arrayWithArray: [code componentsSeparatedByString: @">"]];
    //remove last element
    if([arr count] >= 2){
        [arr removeLastObject];
    //return reassembled string
        return [arr componentsJoinedByString: @">"];
    }
    else
        return nil;//I'm my own parent
}
BOOL isParentOf(NSString *prnt, NSString *chld)
{
    
    NSRange r;
     /*
    NSArray *parray, *carray;
    parray = [NSArray arrayWithArray: [prnt componentsSeparatedByString: @">"]];
    carray = [NSArray arrayWithArray: [chld componentsSeparatedByString: @">"]];
    
    FORALL(parray)
    {
        if([temp isEqualToString: [carray objectAtIndex: __i]] == NO)
            return NO;
    }
    ENDFORALL;
    return YES;
     */
    
    r = [chld rangeOfString: prnt];
    if(r.location == 0) return YES;
    else return NO;
    

}
/* turn a qchar back into a string; cflag is whether to include the comment*/
NSString *stringForQChar(ctQChar *qq, BOOL cflag)
{
    NSString *cdr, *cmt;
    
    
    switch([qq tokentype])
    {
        case TOKEN:
            if([[qq coder] length] > 0)
                cdr = [NSString stringWithFormat: @" [%@]", [qq coder]];
            else
                cdr = [NSString string];
            if(cflag == YES)
            {
                if([[qq extra] length])
                    cmt = [NSString stringWithFormat: @": %@", [qq extra]];
                else
                    cmt = [NSString string];
            }
            else cmt = [NSString string];

            return [NSString stringWithFormat: @"{%@%@%@}",
                [qq buff], cdr, cmt];
            break;
            
        case ENDTOKEN:
            if([[qq coder] length] > 0)
                cdr = [NSString stringWithFormat: @" [%@]", [qq coder]];
            else
                cdr = [NSString string];
            if(cflag == YES)
            {
                if([[qq extra] length])
                    cmt = [NSString stringWithFormat: @": %@", [qq extra]];
                else
                    cmt = [NSString string];
            }
            else cmt = [NSString string];

            return [NSString stringWithFormat: @"{/%@%@%@}",
                [qq buff], cdr, cmt];
            break;
           
        case META:
            if([[qq extra] length])
                return [NSString stringWithFormat: @"{!%@ %@}", [qq buff], [qq extra]];
            else
                return [NSString stringWithFormat: @"{!%@}", [qq buff]];
            break;
        default:
            return [qq buff];
        };
}

NSColor *getColorForInt(int col)
{
    switch(col)
    {
	case red:
	    return  [NSColor redColor];
	    break;
	case yellow:
	    return [NSColor yellowColor];
	    break;
	case green:
	    return [NSColor greenColor] ;
	    break;
	case blue:
	    return [NSColor blueColor] ;
	    break;
	case ltgray:
	    return [NSColor lightGrayColor] ;
	    break;
	case gray:
	    return [NSColor grayColor] ;
	    break;
	case dkgray:
	    return [NSColor darkGrayColor];
	    break;
        case black:
             return [NSColor blackColor];
             break;
	default: ;
    }
}

NSString *codeToLevel(NSString *mycode, int level)
{
    NSArray *a1;
    NSMutableArray *farr = [NSMutableArray array];
    int i,cl;
    if(level == 0) return mycode;
    cl = codeLevel(mycode);
    if(cl <= level) return mycode;
    a1 = [mycode componentsSeparatedByString: @">"];
    for(i = 0; i < level; i++)
        [farr addObject: [a1 objectAtIndex: i]];
    return [farr componentsJoinedByString: @">"];
    
}
int compCodeByLevel(NSString *c1, NSString *c2)
{
    NSArray *a1, *a2;
    int i,n,m, min, lev;
    a1 = [c1 componentsSeparatedByString: @">"];
    a2 = [c2 componentsSeparatedByString: @">"];
    
    n = [a1 count];
    m = [a2 count];
    min = (m > n) ? n : m;
    lev = 0;
    for(i = 0; i < min; i++)
        if([[a1 objectAtIndex: i] isEqualToString: [a2 objectAtIndex: i]] == YES)
            lev++;
        else break;
    
    return lev;

}

NSString *uniqueFileName()
{
    NSString *dt = [[NSDate date] description];
    NSMutableString *ut = [NSMutableString stringWithString: dt];
    [ut replaceOccurrencesOfString: @":" withString: @"--" options: nil range: NSMakeRange(0, [ut length])];
    return ut;
}
NSString *uniqueTmpFileName()
{
    return [NSString stringWithFormat: @"%@fid%@",@"/tmp/", uniqueFileName()];
}

NSString *sec2hhmmss(unsigned l)
{
    int time[3];
    
    time[2] = l/(60*60);
    time[1] = l%(60*60);
    time[0] = time[1]%60;
    time[1] = time[1]/60;
    
    return [NSString stringWithFormat: @"%u:%02u:%02u", time[2], time[1], time[0]];
}

unsigned hhmmss2sec(NSString *tstr)
{
    int tptr, factor, i, ndx, l;
    unsigned time[3], tt;
    unichar ch;
    
    l = [tstr length];
    tptr = 0;
    factor = 1;
    
    time[2] = time[1] = time[0] = 0;
    
    for(i=0; i<l; i++)
    {
        ndx = (l - 1) - i;
        ch = [tstr characterAtIndex: ndx] ;
        if(ch  == ':')
        {
            factor = 1;
            tptr++;
            continue;
        }
        if(ch >= '0' && ch <= '9')
        {
            time[tptr] += (ch - '0') * factor;
            factor *= 10;
        }
    }
    
    tt = 0;
    for(i = 0; i < 3; i++)
    {
        switch(i)
        {
            case 0: tt += time[i]; break;
            case 1: tt += time[i] * 60; break;
            case 2: tt += time[i] *60 * 60; break;
        }
    }
    return tt;
}

BOOL isHHMMSS(NSString *tstr)
{
    int l, i;
    l = [tstr length];
    for(i = 0; i < l; i++)
    {
        if ([tstr characterAtIndex: i] == ':')
            return YES;
    }

    return NO;
}
                
