#!/usr/bin/env python

# Copyright (c) 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution.  The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

"""Ant Tasks Dom Element"""

import xml.dom.minidom, os

class AntTask:
    def __init__(self, document, _name, _body=None, **_attributes):
        """Instantiate an Ant task element
        document, _name=task name, _body=task body, **_attributes=task attributes
        """
        self.Document = document
        self.Root = ""
            
        if _name == None or _name == "":
            raise Exception("No Ant task name")

        taskElement = self.Document.createElement(_name)
        for name in _attributes:
            taskElement.setAttribute(name, _attributes[name])

        if _body != None:
            if isinstance(_body, str):
                text = self.Document.createTextNode(_body)
                taskElement.appendChild(text)
            elif isinstance(_body, list):
                for subtask in _body:
                    taskElement.appendChild(subtask)

        self.Root = taskElement

    def SubTask(self, _name, _body=None, **_attributes):
        """Insert a sub-task into this task"""
        newTask = AntTask(self.Document, _name , _body, **_attributes)
        self.Root.appendChild(newTask.Root)
        return newTask

    def AddSubTask(self, subTask):
        """Insert a existing sub-task into this task"""
        self.Root.appendChild(subTask.Root.cloneNode(True))
        return subTask
        
    def Comment(self, string):
        """Generate a XML comment"""
        self.Root.appendChild(self.Document.createComment(string))

    def Blankline(self):
        """Generate a blank line"""
        self.Root.appendChild(self.Document.createTextNode(""))


class AntBuildFile(AntTask):
    _FileComment = "DO NOT EDIT\nThis file is auto-generated by the build utility\n\nAbstract:\nAuto-generated ANT build file for building Framework modules and platforms\n"
    
    def __init__(self, name, basedir=".", default="all"):
        """Instantiate an Ant build.xml
           name=project name, basedir=project default directory, default=default target of this project
        """
        self.Document = xml.dom.minidom.getDOMImplementation().createDocument(None, "project", None)
        self.Root = self.Document.documentElement
        
        self.Document.insertBefore(self.Document.createComment(self._FileComment), self.Root)
        self.Root.setAttribute("name", name)
        self.Root.setAttribute("basedir", basedir)
        self.Root.setAttribute("default", default)
        
    def Create(self, file):
        """Generate the build.xml using given file path"""
        buildFileDir = os.path.dirname(file)
        if not os.path.exists(buildFileDir):
            os.makedirs(buildFileDir)
            
        f = open(file, "w")
        f.write(self.Document.toprettyxml(2*" ", encoding="UTF-8"))
        f.close()
