export class WFSConverter{
    
    private doc: XMLDocument;
    private version: string;
    
    constructor(doc: XMLDocument){
        this.doc = doc;
        this.version = this.getWFSVersion();
    }

    public readTag(tagName: WFSTag):string{
        var value: string = "";
        if(this.version=="1.0.0"){
            value = this.getValueFromV100(tagName);   
        }else{
            var wfsTagName: string = this.getTagName(tagName);
            value = this.doc.getElementsByTagName(wfsTagName)[0].innerHTML;
        }
        
        return value;
    }

    public readChildNodeTag(docNode: XMLDocument, tagName: WFSTag | string): string{
        var wfsTagName: string = "";
        if(typeof tagName === 'string'){
            wfsTagName = tagName;
        }else{
            wfsTagName = this.getTagName(tagName);
        }
        
        var value: string = "";
        if(docNode.getElementsByTagName(wfsTagName).length>0){
            value = docNode.getElementsByTagName(wfsTagName)[0].innerHTML;
        }
        if(docNode.getElementsByTagName("wfs:"+wfsTagName)[0]){
            value = docNode.getElementsByTagName("wfs:"+wfsTagName)[0].innerHTML;
        }
        return value;
    }

    public readList(tagName: WFSTag): HTMLCollection{
        var wfsTagName: string = this.getTagName(tagName); 
        var featureTypeList: HTMLCollection = this.doc.getElementsByTagName(wfsTagName);
        if(featureTypeList.length==0){
            featureTypeList = this.doc.getElementsByTagName("wfs:"+wfsTagName);
        }

        return featureTypeList;
    }


    public getWFSVersion(): string{
        var version: string|null = this.doc.children[0].getAttribute("version");
        return (version == null)? "" : version;
    }

    public getTagName(tag: WFSTag): string{
        switch(tag){
            case WFSTag.ProviderName:
                return "ows:ProviderName";
            case WFSTag.Title:
                return "ows:Title";
            case WFSTag.FeatureType:
                return "FeatureType";
            case WFSTag.Name:
                return "Name";
            case WFSTag.FeatureTypeTitle:
                return "Title";
            case WFSTag.Abstract:
                return "Abstract";
        }
        
        return "not found";
    }

    public getValueFromV100(tag: WFSTag): string{
        var value: string = "";
        switch(tag){
            case WFSTag.Title:
                
                /* Why doesn't it work?
                var service:XPathResult = this.doc.evaluate("//Service/Title",this.doc,null, XPathResult.STRING_TYPE, null);
                value = service.stringValue; */

                value = this.doc.getElementsByTagName("Title")[0].innerHTML;
            break;
        }

        return value;
    }

}

export enum WFSTag{
    ProviderName, Title, Name, FeatureType, FeatureTypeTitle, Abstract
}