package com.atlassian.bitbucket.internal.branch.model.dao.v1;

import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.bitbucket.ao.AbstractTruncateColumnSubtask;
import com.atlassian.bitbucket.internal.branch.model.dao.v0.AoBranchTypeConfigurationV0;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import net.java.ao.Query;
import net.java.ao.schema.StringLength;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.atlassian.bitbucket.internal.branch.model.dao.v0.AoBranchTypeConfigurationV0.*;

public class MigrateBranchTypeToV1Subtask extends AbstractTruncateColumnSubtask<AoBranchTypeConfigurationV0> {
    private static final String TABLE_NAME = "BRANCH_TYPE";

    public MigrateBranchTypeToV1Subtask(ApplicationPropertiesService applicationPropertiesService) {
        super(applicationPropertiesService, StringLength.MAX_LENGTH, TABLE_NAME, AoBranchTypeConfigurationV0.class);
    }

    @Override
    protected List<String> getColumnNames() {
        return ImmutableList.of(TYPE_ID_COLUMN, TYPE_PREFIX_COLUMN, TYPE_ENABLED_COLUMN);
    }

    @Override
    protected List<String> getRowValues(AoBranchTypeConfigurationV0 row) {
        return ImmutableList.of(row.getTypeId(), row.getPrefix(), String.valueOf(row.isEnabled()));
    }

    @Override
    protected List<AoBranchTypeConfigurationV0> selectRowsToProcess(ActiveObjects ao, int pageSize) {
        AoBranchTypeConfigurationV0[] result = ao.find(AoBranchTypeConfigurationV0.class, Query
                .select()
                .where(Joiner.on(" OR ").join(
                        columnLengthViolatesLimitClause(TYPE_ID_COLUMN, ao),
                        columnLengthViolatesLimitClause(TYPE_PREFIX_COLUMN, ao)))
                .limit(pageSize));

        return result == null ? Collections.emptyList() : Arrays.asList(result);
    }

    @Override
    protected void truncateRowData(AoBranchTypeConfigurationV0 row) {
        row.setTypeId(truncateLongValue(row.getTypeId()));
        row.setPrefix(truncateLongValue(row.getPrefix()));
    }
}
