# bijoe - BI dashboard
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import urlparse
import ConfigParser

from tenant_schemas.utils import tenant_context
from hobo.agent.common.management.commands import hobo_deploy
from hobo.multitenant.settings_loaders import KnownServices

from django.conf import settings


class Command(hobo_deploy.Command):

    def deploy_specifics(self, hobo_environment, tenant):
        super(Command, self).deploy_specifics(hobo_environment, tenant)
        with tenant_context(tenant):
            services = hobo_environment.get('services')
            ini_file = os.path.join(tenant.get_directory(), 'wcs-olap.ini')
            schemas_path = os.path.join(tenant.get_directory(), 'schemas')
            config = ConfigParser.ConfigParser()
            config.read(ini_file)

            new = not(os.path.exists(ini_file))

            if not os.path.exists(schemas_path):
                os.mkdir(schemas_path)
            if not config.has_section('wcs-olap'):
                config.add_section('wcs-olap')
            config.set('wcs-olap', 'cubes_model_dirs', schemas_path)
            pg_dsn_parts = []
            for pg_dsn_part in [('NAME', 'dbname'),
                                ('HOST', 'host'),
                                ('USER', 'user'),
                                ('PASSWORD', 'password'),
                                ('PORT', 'port')]:
                if settings.DATABASES['default'].get(pg_dsn_part[0]):
                    pg_dsn_parts.append('%s=%s' % (
                        pg_dsn_part[1],
                        settings.DATABASES['default'].get(pg_dsn_part[0])))
            config.set('wcs-olap', 'pg_dsn', ' '.join(pg_dsn_parts))

            for service in services:
                if service.get('this'):
                    this = service
                    break
            else:
                raise RuntimeError('unable to find this service')
            our_key = this['secret_key']
            for service in services:
                if (service.get('this') or not service.get('secret_key')
                        or service['service-id'] != 'wcs' or not service.get('base_url')
                        or service.get('secondary')):
                    continue
                base_url = service['base_url']
                schema = (urlparse.urlparse(base_url).netloc.split(':')[0]
                          .replace('.', '_').replace('-', '_'))
                orig = urlparse.urlparse(this.get('base_url')).netloc.split(':')[0]
                their_key = service.get('secret_key')
                key = KnownServices.shared_secret(our_key, their_key)

                if config.has_section(base_url):
                    config.remove_section(base_url)
                config.add_section(base_url)
                config.set(base_url, 'orig', orig)
                config.set(base_url, 'key', key)
                config.set(base_url, 'schema', schema)
                config.set(base_url, 'cubes_label', service.get('title').encode('utf-8'))
                if new:
                    config.set(base_url, 'cubes_slug', service.get('slug'))
            with open(ini_file, 'w') as f:
                config.write(f)	
