import os
import re
import logging
import distutils
import subprocess

from wizard import app, install, resolve, sql, shell, util

import sqlalchemy

def python_config_re(var):
    return re.compile(r'^(%s\s*=\s*)(.*)()$' % re.escape(var), re.M)

seed = {
    'WIZARD_DSN': ('bluechips.ini', python_config_re('sqlalchemy.url')),
    'WIZARD_PREFIX': ('bluechips.ini', python_config_re('prefix')),
    'BEAKER_SESSION_SECRET': ('bluechips.ini', python_config_re('beaker.session.secret')),
    'BEAKER_APP_UUID': ('bluechips.ini', python_config_re('app_instance_uuid')),
}

class Application(app.Application):
    database = 'mysql'

    install_schema = install.ArgSchema('db')
    install_schema.add(install.Arg('username', help='Username for the first user'))
    install_schema.add(install.Arg('name', help="Real name of the first user"))

    parametrized_files = ['bluechips.ini']

    extractors = app.make_extractors(seed)
    substitutions = app.make_substitutions(seed)

    def download(self, version):
        return 'https://github.com/ebroder/bluechips/tarball/%s' % version
        #return 'http://pypi.python.org/packages/source/B/BlueChips/BlueChips-%s.tar.gz' % version

    def checkConfig(self, deployment):
        return os.path.isfile('bluechips.ini')

    def checkWeb(self, deployment):
        # BlueChips installs are private by default, so there's not
        # much we can do here usefully
        return True

    def detectVersion(self, deployment):
        return self.detectVersionFromFile('BlueChips.egg-info/PKG-INFO', re.compile('^(Version: )(.*)$', re.M))

    def install(self, version, options):
        util.soft_unlink('bluechips.ini')

        shell.call('paster', 'make-config', 'BlueChips', 'bluechips.ini')

        ini = open('bluechips.ini').read()
        ini = re.sub(
            (seed['WIZARD_DSN'][1]),
            (r'\1%s\3\nsqlalchemy.pool_recycle = 60') % options.dsn,
            ini)
        open('bluechips.ini', 'w').write(ini)

        shell.call('paster', 'setup-app', 'bluechips.ini')

        ini = open('bluechips.ini').read()
        ini = re.sub(
            (r'\[app:main\]'),
            (r'[filter:prefix]\n'
             r'use = egg:PasteDeploy#prefix\n'
             r'prefix = %s\n'
             r'\n'
             r'[app:main]\n'
             r'filter-with = prefix') % (options.web_path),
            ini)
        open('bluechips.ini', 'w').write(ini)

        meta = sql.connect(options.dsn)
        users = meta.tables['users']
        users.insert().values(
            username=options.username,
            name=options.name,
            resident=1).execute()

    @app.throws_database_errors
    def backup(self, deployment, backup_dir, options):
        sql.backup(backup_dir, deployment)

    @app.throws_database_errors
    def restore(self, deployment, backup_dir, options):
        sql.restore(backup_dir, deployment)

    def upgrade(self, deployment, version, options):
        pass

    @app.throws_database_errors
    def remove(self, deployment, options):
        sql.drop(deployment.dsn)

    def dsnFromExtract(self, deployment):
        if not self.database:
            return None

        vars = self.extract(deployment)
        return sqlalchemy.engine.url.make_url(vars['WIZARD_DSN'])
