package com.njcn.gather.systemops.database.support.mysql;

import com.njcn.gather.systemops.database.component.JdbcExportComponent;
import com.njcn.gather.systemops.database.pojo.enums.BackupStrategyEnum;
import com.njcn.gather.systemops.database.pojo.param.DatabaseRestoreParam;
import com.njcn.gather.systemops.database.pojo.po.DatabaseBackupFile;
import com.njcn.gather.systemops.database.pojo.po.DatabaseConnection;
import com.njcn.gather.systemops.database.pojo.po.DatabaseOperationTask;
import com.njcn.gather.systemops.database.pojo.po.DatabaseRestoreRecord;
import com.njcn.gather.systemops.database.service.DatabaseBackupFileService;
import com.njcn.gather.systemops.database.support.spi.DatabaseRestoreOperator;
import org.springframework.stereotype.Component;

import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * MySQL JDBC_EXPORT 恢复实现。
 */
@Component
public class MysqlJdbcExportRestoreOperator implements DatabaseRestoreOperator {

    private final JdbcExportComponent jdbcExportComponent;
    private final DatabaseBackupFileService databaseBackupFileService;

    public MysqlJdbcExportRestoreOperator(JdbcExportComponent jdbcExportComponent,
                                          DatabaseBackupFileService databaseBackupFileService) {
        this.jdbcExportComponent = jdbcExportComponent;
        this.databaseBackupFileService = databaseBackupFileService;
    }

    @Override
    public boolean support(String dbType, String backupStrategy) {
        return "MYSQL".equalsIgnoreCase(dbType) && BackupStrategyEnum.JDBC_EXPORT.name().equals(backupStrategy);
    }

    @Override
    public void executeRestore(DatabaseOperationTask task, DatabaseRestoreRecord record, DatabaseBackupFile backupFile,
                               DatabaseConnection connection, String password, DatabaseRestoreParam.CreateParam param) throws Exception {
        Path dataFilePath = databaseBackupFileService.resolveManagedPath(backupFile, backupFile.getFilePath());
        Path metadataFilePath = databaseBackupFileService.resolveManagedPath(backupFile, backupFile.getMetadataFilePath());
        try (Connection jdbcConnection = DriverManager.getConnection(MysqlJdbcUrlUtil.build(connection), connection.getUsername(), password)) {
            jdbcExportComponent.importCsv(jdbcConnection, dataFilePath, metadataFilePath,
                    connection.getDbType(), record.getRestoreMode(), null);
        }
    }
}
