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

import javax.annotation.ParametersAreNonnullByDefault;

import com.yandex.direct.api.v5.feeds.FeedUpdateItem;
import com.yandex.direct.api.v5.feeds.FileFeedUpdate;
import com.yandex.direct.api.v5.feeds.UrlFeedUpdate;

import ru.yandex.direct.api.v5.common.GeneralUtil;
import ru.yandex.direct.api.v5.converter.ModelChangesHelper;
import ru.yandex.direct.core.entity.feed.model.Feed;
import ru.yandex.direct.model.ModelChanges;

@ParametersAreNonnullByDefault
public class UpdateRequestConverter {

    public static ModelChanges<Feed> convert(FeedUpdateItem item) {
        ModelChanges<Feed> changes = new ModelChanges<>(item.getId(), Feed.class);
        changes.processNotNull(item.getName(), Feed.NAME);
        UrlFeedUpdate urlFeed = item.getUrlFeed();
        if (urlFeed != null) {
            changes.processNotNull(urlFeed.getUrl(), Feed.URL);
            changes.processNotNull(urlFeed.getRemoveUtmTags(), Feed.IS_REMOVE_UTM, GeneralUtil::yesNoToBoolean);
            ModelChangesHelper.processJaxbElement(changes, urlFeed.getLogin(), Feed.LOGIN);
            ModelChangesHelper.processJaxbElement(changes, urlFeed.getPassword(), Feed.PLAIN_PASSWORD);
        }
        FileFeedUpdate fileFeed = item.getFileFeed();
        if (fileFeed != null) {
            changes.processNotNull(fileFeed.getFilename(), Feed.FILENAME);
            byte[] data = fileFeed.getData();
            if (data != null) {
                changes.processNotNull(data, Feed.FILE_DATA);
            }
        }
        return changes;
    }
}
