//
//  OmXmlHelper.m
//  misc_test_app
//
//  Created by david van brink on 7/27/10.
//  Copyright 2010 omino.com. All rights reserved.
//

#import "OmXmlHelper.h"
#include <stdio.h>


@implementation OmXmlHelper

-(bool)beginWriting:(char *)filePath comment:(char *)comment outerElement:(char *)outerElement;
{
    fh = fopen(filePath, "w");
    if(!fh)
        return false;
    
    fprintf(fh,"<!-- %s -->",comment);
    self->currentElementEmpty = false;
    [self beginElement:outerElement];
    return true;
}

// on the first un-emptying thing, close the opening tag of the element
static void unempty(OmXmlHelper *x)
{
    if(x->currentElementEmpty)
    {
        fprintf(x->fh,">");
        x->currentElementEmpty = false;
    }
}



-(void)beginElement:(char *)element;
{
    unempty(self);
    fprintf(self->fh,"<%s",element);
    self->currentElementEmpty = true;
    self->elements[self->depth] = element;
    self->depth++;
}

-(void)addAttribute:(char *)attribute value:(char *)attributeValue;
{
    NSString *s = [NSString stringWithCString:attributeValue encoding:NSASCIIStringEncoding];
    s = escapeForHtml(s);
    NSSTRING_TO_C(s,sc);
    fprintf(self->fh," %s=\"%s\"",attribute,sc);
}

-(void)addText:(char *)text;
{
    unempty(self);
    fprintf(self->fh,"%s",text);
}

-(void)endElement;
{
    if(self->depth == 0)
        return;
    
    self->depth--;
    
    if(self->currentElementEmpty)
        fprintf(self->fh,"/>\n");
    else
        fprintf(self->fh,"</%s>\n",self->elements[self->depth]);
    self->currentElementEmpty = false;
}

// Close any open elements, and close the file
-(bool)close;
{
    while(self->depth > 0)
        [self endElement];
    fclose(self->fh);
    self->fh = 0;
    return true;
}

NSString *escapeForHtml(NSString *s)
{
    s = [s stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
    s = [s stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
    s = [s stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    s = [s stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"];
    s = [s stringByReplacingOccurrencesOfString:@"\'" withString:@"&apos;"];
    return s;
}



@end
