from __future__ import absolute_import

import os

BOAT_DIR = '.boat'

class InstanceError(Exception):
    pass

class Application(object):
    def __init__(self, instance_path):
        self.instance_path = instance_path
        self.static_folder = os.path.join(__path__[0], 'static')
        self.database_path = os.path.join(self.instance_path, BOAT_DIR, 'boat.db')

def iter_path_and_parents(path):
    path = os.path.abspath(path)
    while path != '/':
        yield path
        path = os.path.abspath(os.path.join(path, '..'))
    yield path

def find_instance_path():
    for instance_path in iter_path_and_parents('.'):
        if os.path.exists(os.path.join(instance_path, BOAT_DIR)):
            return instance_path
    return None

def create_instance_path():
    instance_path = find_instance_path()
    if instance_path:
        raise InstanceError, "Directory already part of boat project (%s)" % \
            instance_path

    instance_path = os.path.abspath('.')
    os.mkdir(os.path.join(instance_path, BOAT_DIR))
    return instance_path

def create_app(init=False):
    import boat.db
    import boat.webcomic

    if init:
        instance_path = create_instance_path()
    else:
        instance_path = find_instance_path()

    if not instance_path:
        raise InstanceError, "Can't find %s dir in current directory tree" % \
            BOAT_DIR

    app = Application(instance_path)
    boat.db.register(app, init)
    boat.webcomic.register(app, init)

    return app
