import subprocess

from . import UbacDatabase, parse_list


class UbacMysql(UbacDatabase):
    DEST_SUBDIR = 'mysql'

    @classmethod
    def from_section(cls, section, remote):
        return cls(
            remote,
            list(parse_list(section['mysql_dbs'])),
            freshness=int(section['check_since']),
            nb_to_keep=int(section['nb_to_keep']),
        )

    def list_dbs(self):
        for db in super(UbacMysql, self).list_dbs():
            if db in ['performance_schema', 'information_schema']:
                continue
            yield db

    def list_available_dbs(self):
        p = subprocess.Popen(
            ["mysql", "-N"], stdout=subprocess.PIPE, stdin=subprocess.PIPE
        )
        stdout, stderr = p.communicate('show databases;'.encode('utf-8'))
        assert p.wait() == 0
        return stdout

    def dump_db(self, dbname):
        cmd = ["mysqldump", dbname]
        for db in super(UbacMysql, self).dump_db(cmd):
            yield db
