class FileChooserUi(DialogUi):
    def __init__(self, owner, fileTypes):
        self.owner = owner
        self.fileTypes = fileTypes
        self.size = Vector(600, 400)
        self.root = os.path.join(os.getcwd(), 'mods').replace('\\', '/')
        DialogUi.__init__(self, 'filechooser', PixelRect(0, 0, self.size.x, self.size.y))

        #Center this on the owner view
        ownerPosition = self.owner.view.getPosition()
        ownerSize = self.owner.view.getSize()
        position = Vector()
        position.x = ownerPosition.x + (ownerSize.x / 2.0) - (self.size.x / 2.0)
        position.y = ownerPosition.y + (ownerSize.y / 2.0) - (self.size.y / 2.0)
        self.view.setPosition(position)

        #Register UI callbacks
        self.view.register('populate', self.onPopulate)
        self.view.register('confirm', self.onConfirm)
        self.view.register('cancel', self.onCancel)
        self.load('html/filechooser.html')
        self.view.show()
        self.view.setModal(True)
        game.gui.focusView(self.view)

    def onPopulate(self, view, args):
        Log.info("Populating file chooser.")
        commands = []
        for fileType in self.fileTypes:
            commands.append("App.fileTypes.push('%s');" % (fileType,))
        commands.append("App.set('root', App.File.create({name: '%s', path: '%s'}));" % (os.path.split(self.root)[1], self.root))
        commands.append("App.root.set('isFolder', true);")
        commands.append("App.root.set('isCollapsed', false);")
        commands.append("App.folders['%s'] = App.root;" % (self.root,))
        for path, dirs, files in os.walk(self.root):
            path = path.replace('\\', '/')
            commands.append("var parent = App.folders['%s'];" % path)
            for d in dirs:
                fullDir = os.path.join(path, d).replace('\\', '/')
                commands.append("var child = App.File.create({name: '%s', path: '%s', isFolder: true});" % (d, fullDir))
                commands.append("parent.files.pushObject(child);")
                commands.append("App.folders['%s'] = child;" % fullDir)
            for f in files:
                if os.path.splitext(f)[1] in self.fileTypes:
                    filePath = os.path.join(path, f).replace('\\', '/')
                    commands.append("parent.files.pushObject(App.File.create({name: '%s', path: '%s'}));" % (f, filePath))
        self.view.execute(commands)

    def onConfirm(self, view, args):
        self.destroy()
        result = args[1].toString()
        if not os.path.splitext(result)[1]:
            #If the path does not have an extension then give it the first file type extension
            result += self.fileTypes[0]
        self.owner.chooseFile(result)

    def onCancel(self, view, args):
        self.destroy()
        self.owner.chooseFile('')

    def destroy(self):
        game.gui.destroyView(self.view.name)
