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

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.systemops.database.component.DataPumpCommandExecutor;
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.support.spi.DatabaseRestoreOperator;
import com.njcn.gather.systemops.database.util.DatabaseFileNameUtil;
import org.springframework.stereotype.Component;

/**
 * Oracle DATA_PUMP 恢复实现。
 */
@Component
public class OracleDataPumpRestoreOperator implements DatabaseRestoreOperator {

    private final DataPumpCommandExecutor dataPumpCommandExecutor;

    public OracleDataPumpRestoreOperator(DataPumpCommandExecutor dataPumpCommandExecutor) {
        this.dataPumpCommandExecutor = dataPumpCommandExecutor;
    }

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

    @Override
    public void executeRestore(DatabaseOperationTask task, DatabaseRestoreRecord record, DatabaseBackupFile backupFile,
                               DatabaseConnection connection, String password, DatabaseRestoreParam.CreateParam param) {
        DataPumpCommandExecutor.CommandResult result = dataPumpCommandExecutor.impdp(connection, password,
                backupFile.getDirectoryName(), backupFile.getDumpFileName(), buildRestoreLogName(task),
                record.getTableExistsAction());
        if (!Boolean.TRUE.equals(result.getSuccess())) {
            throw new BusinessException(CommonResponseEnum.FAIL, "Data Pump 恢复失败：" + result.getOutput());
        }
    }

    private String buildRestoreLogName(DatabaseOperationTask task) {
        return DatabaseFileNameUtil.appendTodayWithTask(task.getTaskNo() + "_restore.log", task.getTaskNo());
    }
}
