package ru.yandex.webmaster3.core.semantic.review_business.model.impl.json;

import com.google.common.base.Preconditions;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.core.semantic.review_business.model.ReviewModeration;
import ru.yandex.webmaster3.core.semantic.review_business.util.DateHelper;

import static ru.yandex.webmaster3.core.semantic.review_business.model.impl.ReviewModerationAttributes.*;

/**
 * Helps to convert {@see ReviewModeration} to {@see JSONObject} and vise-versa
 *
 * @author Dima Schitinin <dimas@yandex-team.ru>
 */
public final class ReviewModerationJsonConversions {
    private static final Logger log = LoggerFactory.getLogger(ReviewModerationJsonConversions.class);

    private ReviewModerationJsonConversions() {
    }

    /**
     * Use {@link #fromJson(String)} (throws {@link JSONException}) and {@link #safeFromJson(String)} instead
     */
    @Deprecated
    public static ReviewModerationOverJson fromJson(final JSONObject json) {
        return new ReviewModerationOverJson(json);
    }
    public static ReviewModerationOverJson fromJson(final String json) throws JSONException {
        return new ReviewModerationOverJson(json);
    }
    public static ReviewModerationOverJson safeFromJson(final String json) {
        try {
            return fromJson(json);
        } catch (JSONException e) {
            log.error("Error while parsing Moderation2 from json", e);
            return null;
        }
    }

    public static JSONObject toJson(final ReviewModeration moderation) throws JSONException {
        Preconditions.checkNotNull(moderation, "Unable to write null ReviewModeration to JSON");
            return new JSONObject().
                    putOpt(STATUS, moderation.getStatus()).
                    putOpt(CUSTOM_REJECTION_TEXT, moderation.getCustomRejectionText()).
                    putOpt(HANDLER, moderation.getHandler()).
                    putOpt(TIME, DateHelper.safeWrite(moderation.getTime())).
                    putOpt(NOTE, moderation.getNote()).
                    putOpt(REJECTION_TEXT, moderation.getRejectionText());
    }
    public static String toJsonString(final ReviewModeration moderation) throws JSONException {
        JSONObject obj;
        obj = toJson(moderation);

        return obj.toString();
    }
    public static String safeToJsonString(final ReviewModeration moderation) {
        try {
            return toJsonString(moderation);
        } catch (JSONException e) {
            log.error("Error while convert ReviewModeration to JSON", e);
            return null;
        }
    }


}

