import os
from django.core.management import BaseCommand
from django.db import connections
from django.db import models
from django.conf import settings

ROOT_URL = settings.BASE_DIR

SQL_URL = os.path.join(ROOT_URL, 'sql')


class InItDBLog(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32, null=False)
    run_time = models.DateTimeField(auto_created=True, null=False)

    class Meta:
        db_table = "init_db_log"


class Command(BaseCommand):
    help = '初始化数据库'

    def get_sql(self, sql_file):
        with open(os.path.join(SQL_URL, sql_file), "r", encoding="utf-8") as f:
            sql_list = f.read().split(';')[:-1]
        return sql_list

    def get_sql_file_list(self):
        sql_file = []
        for _, _, files in os.walk(SQL_URL):
            sql_file.extend(files)
            sql_file.sort()
        return sql_file

    def handle(self, *args, **options):
        step = 1
        sql_file_list = self.get_sql_file_list()
        sql_file_list.remove('log.sql')
        if 'README.md' in sql_file_list:
            sql_file_list.remove('README.md')
        sfl = []
        for i in sql_file_list:
            sfl.append(int(i.split('.')[0]))
        sfl.sort()
        print(sfl)

        with connections["test"].cursor() as c:
            sql_list = self.get_sql('log.sql')
            for sql in sql_list:
                c.execute(sql)
        try:
            logs = InItDBLog.objects.using("test").all()
        except Exception:
            logs = None
        if len(logs) == 0:
            for sql_file in sfl:
                sql_file = str(sql_file) + '.sql'
                with connections["test"].cursor() as c:
                    sql_list = self.get_sql(sql_file)
                    for sql in sql_list:
                        c.execute(sql)
                InItDBLog.objects.using("test").create(name=sql_file)
            self.stdout.write("数据库初始化完成")

        else:
            flag = True
            logs_list = InItDBLog.objects.using("test").all()
            logs = []
            for i in logs_list:
                logs.append(int(i.name.split(".")[0]))
            logs.sort()
            for log in logs:
                if step == log and str(log) + '.sql' in sql_file_list:
                    sql_file_list.remove(str(log) + '.sql')
                    step += 1
                else:
                    self.stdout.write("数据库初始化失败，init_db_log存在错误数据")
                    return

            if len(sql_file_list) != 0:
                sql_file_list.sort()
                for sql_file in sql_file_list:
                    if int(sql_file.split('.')[0]) == step:
                        with connections["test"].cursor() as c:
                            sql_list = self.get_sql(sql_file)
                            for sql in sql_list:
                                c.execute(sql)
                        InItDBLog.objects.using("test").create(name=sql_file)
                        step += 1
                    else:
                        flag = False
                        break
                if flag:
                    self.stdout.write("数据库初始化完成")
                else:
                    self.stdout.write("数据库初始化失败，init_db_log存在错误数据")
            else:
                self.stdout.write("数据库初始化完成")
