import csv
import os
import subprocess
from pathlib import Path
import zipfile
from datetime import datetime
from path_info import PathInfo
import config
from ftp_client import FtpClient
from db_info import DatabaseInfo


def run_command(cmd, logfile):
    with open(logfile, 'wb') as stream:
        p = subprocess.Popen(cmd, stdout=stream, stderr=stream)
        p.wait()


def task_scheduler(logfile):
    run_command('schtasks /query /v /fo CSV', logfile)


def task_manager(logfile):
    run_command('tasklist /fo CSV', logfile)


def shared_files(logfile):
    run_command('openfiles /Query /fo CSV', logfile)


def model_datasources(cfg, model_file: Path, logfile):
    cmd = f'"{cfg.cognos7.program_dir}\\runmac32.exe" "{cfg.tools_dir}\\VBS\\list-datasources-c11.mac" ' \
          + f'"{model_file.parent}","{model_file.name}","{logfile}"'
    p = subprocess.Popen(cmd)
    p.wait()


def datasources_all_models(cfg: config.Config):
    os.makedirs(cfg.tasks_dir + '\\config\\models', exist_ok=True)
    for model_file in Path(cfg.system_dir + '\\Models').glob('*.pyj'):
        model_datasources(cfg, model_file, cfg.tasks_dir + '\\config\\models\\' + model_file.name + '.log')


def database_info(cfg: config.Config):
    dbinfo = DatabaseInfo()
    result = []
    for db in dbinfo.databases():
        result.extend(dbinfo.table_size(db[0]))
    csv_file = cfg.tasks_dir + '\\logs\\db_info.csv'
    with open(csv_file, 'w', encoding='latin-1', newline='') as fwh:
        wr = csv.writer(fwh, delimiter=';')
        wr.writerow(['DatabaseName', 'SchemaName', 'TableName', 'RowCounts', 'TotalSpaceKB', 'UsedSpaceKB', 'UnusedSpaceKB', 'LastChanged'])
        for row in result:
            wr.writerow(row)
    return result


def zip_to_file(base_dir, zip_file):
    filter = ['config/*', 'config/info/*', 'config/models/*', 'logs/*', '*.ini', '*.bat']

    with zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zip:
        for f in filter:
            for e in Path(base_dir).glob(f):
                if '.zip' not in e.name:
                    zip.write(e, e.relative_to(base_dir))


if __name__ == '__main__':
    cfg = config.Config()

    # Aufgabenplanung aktueller Stand
    task_scheduler(cfg.tasks_dir + '\\logs\\schtasks.csv')
    # Laufende Prozesse
    task_manager(cfg.tasks_dir + '\\logs\\tasklist.csv')
    # aktuelle Freigabe-Sessions
    shared_files(cfg.tasks_dir + '\\logs\\openfiles.csv')
    # Tabellengrößen
    database_info(cfg)

    datasources_all_models(cfg)
    # Liste aller Dateien im GAPS-Verzeichnis
    # filename;size;cdate;mdate
    ti = PathInfo()
    ti.check_dir(cfg.portal_dir)
    ti.write_logfile(cfg.tasks_dir + '\\logs\\path_info.csv')

    # Logdateien aus Tasks/logs und System/prot
    timestamp = datetime.now().strftime('%Y-%m-%d_%H%M%S')
    zip_file = f"{cfg.tasks_dir}\\logs\\{cfg.kunde_safe}_{timestamp}.zip"
    zip_to_file(cfg.tasks_dir, zip_file)

    # Upload auf FTP
    FtpClient().upload(zip_file)
