package ru.yandex.direct.api.v5.entity.retargetinglists.converter;

import java.util.ArrayList;
import java.util.List;

import com.yandex.direct.api.v5.retargetinglists.RetargetingListUpdateItem;
import com.yandex.direct.api.v5.retargetinglists.UpdateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import ru.yandex.direct.core.entity.retargeting.model.RetargetingCondition;
import ru.yandex.direct.model.ModelChanges;

import static ru.yandex.direct.utils.CommonUtils.nvl;

@Component
public class UpdateRequestConverter implements Converter<UpdateRequest, List<ModelChanges<RetargetingCondition>>> {
    @Autowired
    AddRequestConverter addRequestConverter;

    @Override
    public List<ModelChanges<RetargetingCondition>> convert(UpdateRequest request) {
        List<ModelChanges<RetargetingCondition>> changesList =
                new ArrayList<>(request.getRetargetingLists().size());

        for (RetargetingListUpdateItem item : request.getRetargetingLists()) {
            ModelChanges<RetargetingCondition> changes = new ModelChanges<>(item.getId(), RetargetingCondition.class);

            changes.processNotNull(item.getName(), RetargetingCondition.NAME);

            if (item.getDescription() != null) {
                changes.process(nvl(item.getDescription().getValue(), ""), RetargetingCondition.DESCRIPTION);
            }

            if (!item.getRules().isEmpty()) {
                changes.processNotNull(item.getRules(), RetargetingCondition.RULES,
                        r -> addRequestConverter.convertRules(r));
            }

            changesList.add(changes);
        }
        return changesList;
    }
}
