# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import dbs
from south.v2 import DataMigration
from django.db import models

db = dbs["pubdb"]

class Migration(DataMigration):

    def forwards(self, orm):
        """
        Copy data from legacy MySQL tables to new models.
        """

        if db.backend_name != "mysql":
            return
        tables = set(row[0] for row in db.execute("SHOW TABLES"))
        if "client" in tables:
            db.execute(
                """
                INSERT INTO pubdb_client (id, client_handle, base_uri, bpki_cert, bpki_glue, last_cms_timestamp)
                SELECT client_id, client_handle, base_uri, bpki_cert, bpki_glue, last_cms_timestamp FROM client
                """)

    def backwards(self, orm):
        """
        Roll back this migration.  Disabled by default, because it's dangerous.
        """

        enable_dangerous_rollback = False

        if db.backend_name != "mysql":
            return

        elif not enable_dangerous_rollback:
            raise RuntimeError("Reversing this transformation is dangerous, edit %s if you're sure you want to do this" % __file__)

        for table in [row[0] for row in db.execute("SHOW TABLES") if row[0].startswith("pubdb_")]:
            db.execute("DELETE FROM `%s`" % table)

    models = {
        u'pubdb.client': {
            'Meta': {'object_name': 'Client'},
            'base_uri': ('django.db.models.fields.TextField', [], {}),
            'bpki_cert': ('rpki.fields.BlobField', [], {'default': 'None', 'blank': 'True'}),
            'bpki_glue': ('rpki.fields.BlobField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
            'client_handle': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_cms_timestamp': ('rpki.fields.SundialField', [], {'null': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['pubdb']
    symmetrical = True
