package ru.yandex.qe.dispenser.ws.allocation;

import java.util.Collection;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import ru.yandex.qe.dispenser.client.v1.impl.DispenserConfig;
import ru.yandex.qe.dispenser.domain.MessageHelper;
import ru.yandex.qe.dispenser.domain.Person;
import ru.yandex.qe.dispenser.domain.QuotaChangeRequest;
import ru.yandex.qe.dispenser.domain.dao.property.PropertyReader;
import ru.yandex.qe.dispenser.domain.exception.SingleMessageException;
import ru.yandex.qe.dispenser.domain.hierarchy.Hierarchy;
import ru.yandex.qe.dispenser.domain.property.Property;
import ru.yandex.qe.dispenser.domain.tracker.TrackerManager;
import ru.yandex.qe.dispenser.ws.bot.Provider;
import ru.yandex.startrek.client.model.CollectionUpdate;
import ru.yandex.startrek.client.model.CommentCreate;
import ru.yandex.startrek.client.model.IssueUpdate;

@Component
public class SolomonRequestAllocationWorkflow extends AssigneeAndSummonRequestAllocationWorkflow {
    private static final String PROVIDER_PROPERTY_KEY = "solomon";
    private static final String ASSIGNEE_DEFAULT = "guschin";

    @Inject
    public SolomonRequestAllocationWorkflow(final TrackerManager trackerManager,
                                            final MessageHelper messageHelper,
                                            @Value("${qe.app.environment}") final DispenserConfig.Environment environment,
                                            @Value("${dispenser.cluster.prefix}") final String clusterPrefix) {
        super(Provider.SOLOMON, trackerManager, messageHelper, environment, clusterPrefix, PROVIDER_PROPERTY_KEY, ASSIGNEE_DEFAULT, false);
    }

    @Override
    public void onAllocationRequest(final QuotaChangeRequest request, final Collection<QuotaChangeRequest.Change> changes,
                                    final Person performer, final boolean suppressSummon) {
        final String issueKey = request.getTrackerIssueKey();
        if (issueKey == null) {
            throw SingleMessageException.illegalArgument("cannot.allocate.without.ticket");
        }

        final PropertyReader propertyReader = Hierarchy.get().getPropertyReader();

        final String assignee = propertyReader.read("solomonWorkflow", "allocatorPerson")
                .map(p -> p.getValue().getAs(Property.Type.STRING)).orElse("guschin");

        final String comment = formatAllocateComment(request, changes, performer, assignee);

        final IssueUpdate update = IssueUpdate
                .assignee(assignee)
                .update("followers", CollectionUpdate.add(performer.getLogin()))
                .comment(CommentCreate.comment(comment).build())
                .build();

        trackerManager.updateIssue(issueKey, update);
    }
}
