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

import com.google.common.base.Preconditions;
import org.json.JSONException;
import org.json.JSONObject;
import ru.yandex.webmaster3.core.semantic.review_business.biz.model.Comment;
import ru.yandex.webmaster3.core.semantic.review_business.util.DateHelper;

import java.util.Date;

import static com.google.common.base.Strings.emptyToNull;
import static ru.yandex.webmaster3.core.semantic.review_business.biz.model.impl.CommentAttributes.*;

/**
 * @author Dima Schitinin <dimas@yandex-team.ru>
 */
public class CommentOverJson extends Comment {

    private final JSONObject json;

    /**
     * This implementation breaks the contract for hashCode (because hashCode is counted
     * on top of all get methods of Object and JSONObject is mutable and cannot be controlled from
     * this implementation)
     * Visibility will be changed to package private (in case of necessity
     * of usage in constructing of high-level objects) or removed completely
     */
    @Deprecated
    public CommentOverJson(final JSONObject json) {
        Preconditions.checkNotNull(json, "Unable to create Comment over null JSON");
        this.json = json;
    }

    public CommentOverJson(final String json) throws JSONException {
        Preconditions.checkNotNull(emptyToNull(json), "Unable to create Comment over empty JSON string");
        this.json = new JSONObject(json);
    }

    @Override
    public String getText() {
        return json.optString(TEXT, null);
    }

    @Override
    public Date getPublishedDate() {
        return DateHelper.read(json.optString(PUBLISHED_DATE, null));
    }

    @Override
    public Long getBizId() {
        return json.optLong(BIZ_ID);
    }

    @Override
    public String getReviewId() {
        return json.optString(REVIEW_ID, null);
    }

    @Override
    public Long getReviewAuthorUid() {
        return json.optLong(REVIEW_AUTHOR_UID);
    }
}

