#w.c.s. -  web application for online forms
# Copyright (C) 2005-2014  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function

import os
import sys
import psycopg2
import psycopg2.errorcodes
from datetime import datetime
from shutil import rmtree

from django.utils import six

from ..qommon.ctl import Command, make_option


class CmdDeleteTenant(Command):
    name = 'delete_tenant'

    def __init__(self):
        Command.__init__(self, [
                make_option('--force-drop', action='store_true', default=False,
                            dest='force_drop'),
                ])

    def execute(self, base_options, sub_options, args):
        from .. import publisher

        publisher.WcsPublisher.configure(self.config)
        pub = publisher.WcsPublisher.create_publisher(
                register_tld_names=False)

        hostname = args[0]
        pub.app_dir = os.path.join(pub.app_dir, hostname)
        pub.set_config()
        self.delete_tenant(pub, sub_options, args)

    def delete_tenant(self, pub, options, args):
        if options.force_drop:
            rmtree(pub.app_dir)
        else:
            deletion_date = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
            os.rename(pub.app_dir, pub.app_dir + '_removed_%s.invalid' % deletion_date)

        # do this only if the wcs has a postgresql configuration
        if pub.is_using_postgresql():
            postgresql_cfg = {}
            for k, v in pub.cfg['postgresql'].items():
                if v and isinstance(v, six.string_types):
                    postgresql_cfg[k] = v

            # if there's a createdb-connection-params, we can do a DROP DATABASE with
            # the option --force-drop, rename it if not
            createdb_cfg = pub.cfg['postgresql'].get('createdb-connection-params', {})
            createdb = True
            if not createdb_cfg:
                createdb_cfg = postgresql_cfg
                createdb = False
            try:
                pgconn = psycopg2.connect(**createdb_cfg)
            except psycopg2.Error as e:
                print('failed to connect to postgresql (%s)' % psycopg2.errorcodes.lookup(e.pgcode),
                        file=sys.stderr)
                return

            pgconn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
            cur = pgconn.cursor()
            try:
                dbname = pub.cfg['postgresql']['database']
                if createdb:
                    if options.force_drop:
                        cur.execute('DROP DATABASE %s' % dbname)
                    else:
                        cur.execute('ALTER DATABASE %s RENAME TO removed_%s_%s' % (dbname,
                                                                                   deletion_date,
                                                                                   dbname))
                else:
                    cur.execute("""SELECT table_name
                                   FROM information_schema.tables
                                   WHERE table_schema = 'public'
                                   AND table_type = 'BASE TABLE'""")

                    tables_names = [x[0] for x in cur.fetchall()]

                    if options.force_drop:
                        for table_name in tables_names:
                            cur.execute('DROP TABLE %s CASCADE' % table_name)

                    else:
                        schema_name = 'removed_%s_%s' % (deletion_date, dbname)
                        cur.execute("CREATE SCHEMA %s" % schema_name[:63])
                        for table_name in tables_names:
                            cur.execute('ALTER TABLE %s SET SCHEMA %s' %
                                        (table_name, schema_name[:63]))

            except psycopg2.Error as e:
                print('failed to alter database %s: (%s)' % (
                        createdb_cfg['database'], psycopg2.errorcodes.lookup(e.pgcode)),
                        file=sys.stderr)
                return

            cur.close()

CmdDeleteTenant.register()
