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 ru.yandex.webmaster3.core.semantic.review_business.model.ReviewModeration;
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.model.impl.ReviewModerationAttributes.*;

/**
 * {@see ReviewModeration} that read its properties from {@see JSONObject}.
 *
 * @author Dima Schitinin <dimas@yandex-team.ru>
 */
public class ReviewModerationOverJson extends ReviewModeration {
    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
     */
    protected ReviewModerationOverJson(final JSONObject json) {
        Preconditions.checkNotNull(json, "Unable to create ReviewModeration over null JSON");
        this.json = json;
    }
    public ReviewModerationOverJson(final String json) throws JSONException {
        Preconditions.checkNotNull(emptyToNull(json), "Unable to create ReviewModeration over empty JSON string");
        this.json = new JSONObject(json);
    }


    @Override
    public Status getStatus() {
        return ReviewModerationOverJson.Status.safeValueOf(json.optString(STATUS, null));
    }

    @Override
    public String getCustomRejectionText() {
        return json.optString(CUSTOM_REJECTION_TEXT, null);
    }

    @Override
    public Handler getHandler() {
        return ReviewModerationOverJson.Handler.safeValueOf(json.optString(HANDLER, null));
    }

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

    @Override
    public String getNote() {
        return json.optString(NOTE, null);
    }

    @Override
    public String getRejectionText() {
        return json.optString(REJECTION_TEXT, null);
    }
}

