# coding=utf-8
import sys

from django.core.management import BaseCommand
from django.db.utils import IntegrityError
from django.db import connection


def confirm():
    op = raw_input()
    return op.strip() == 'y'


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--database', help='select op database')
        parser.add_argument('--save', type=int)

    def handle(self, *args, **options):
        db = options['database']
        is_save = options['save']

        ref_tb_fmt = ("SELECT `CONSTRAINT_SCHEMA`, `TABLE_NAME` FROM "
                      "`information_schema`.`REFERENTIAL_CONSTRAINTS` WHERE "
                      "`REFERENCED_TABLE_NAME` = 'api_city' AND `CONSTRAINT_SCHEMA`='{db}';")

        src2dst = {
            'xiangfan': 'xiangyang',
            'luan': 'liuan',
            '东阳': 'dongyang',
            ' yiwu': 'yiwu'
        }

        cursor = connection.cursor()
        sql = ref_tb_fmt.format(db=db)
        cursor.execute(sql)
        print("Find ref tables:")
        tables = []
        for (db, tb) in cursor.fetchall():
            print(db, tb)
            tables.append(tb)

        sql_fmt = """
        SELECT `id`, `city_id` FROM `{db}`.`{tb}` WHERE `city_id` in {vals}
        """

        for tb in tables:
            sql = sql_fmt.format(db=db, tb=tb, vals=tuple(src2dst.keys()))
            cursor.execute(sql)
            for (id_, cid) in cursor.fetchall():
                sql = """
                UPDATE `{db}`.`{tb}` SET `city_id` = '{new}' WHERE `id` = {id}
                """.format(db=db, tb=tb, new=src2dst[cid], id=id_)
                print(sql.strip())
                if is_save and confirm():
                    try:
                        cursor.execute(sql)
                    except IntegrityError as e:
                        print("Error: {e}".format(e=e))
                print('-' * 30)
