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

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.core.semantic.review_business.biz.model.Comment;
import ru.yandex.webmaster3.core.semantic.review_business.util.DateHelper;

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

/**
 * Helps to convert {@link Comment} to JSON object and vise-versa.
 *
 * @author Dima Schitinin <dimas@yandex-team.ru>
 */
public class CommentJsonConversions {
    private static final Logger log = LoggerFactory.getLogger(CommentJsonConversions.class);

    private CommentJsonConversions() {
    }

    /**
     * Use {@link #fromJson(String)} (throws {@link JSONException}) and {@link #safeFromJson(String)} instead
     */
    @Deprecated
    public static Comment fromJson(final JSONObject json) {
        return new CommentOverJson(json);
    }

    public static Comment fromJson(final String json) throws JSONException {
        return new CommentOverJson(json);
    }

    public static Comment safeFromJson(final String json) {
        try {
            return fromJson(json);
        } catch (JSONException e) {
            log.error("Error while parsing Comment from json", e);
            return null;
        }
    }

    /**
     * Use {@link #toJsonString(ru.yandex.webmaster3.core.semantic.review_business.biz.model.Comment)} instead
     */
    @Deprecated
    public static JSONObject toJson(final Comment comment)
            throws JSONException {
        return new JSONObject().
                putOpt(BIZ_ID, comment.getBizId()).
                putOpt(TEXT, comment.getText()).
                putOpt(PUBLISHED_DATE, DateHelper.safeWrite(comment.getPublishedDate())).
                putOpt(REVIEW_ID, comment.getReviewId()).
                putOpt(REVIEW_AUTHOR_UID, comment.getReviewAuthorUid());
    }

    public static String toJsonString(final Comment comment) throws JSONException {
        JSONObject obj;
        obj = toJson(comment);
        return obj.toString();
    }

    /**
     * Use {@link #safeToJsonString(ru.yandex.webmaster3.core.semantic.review_business.biz.model.Comment)} instead
     */
    @Deprecated
    public static JSONObject safeToJson(final Comment comment) {
        try {
            return toJson(comment);
        } catch (JSONException e) {
            log.error(
                    "Error while convert Comment to JSON", e);
            return null;
        }
    }

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

