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

import org.json.JSONException;
import org.json.JSONObject;
import ru.yandex.webmaster3.core.semantic.review_business.model.LinkToOriginReview;
import ru.yandex.webmaster3.core.semantic.review_business.model.impl.LinkToOriginReviewAttributes;

import java.util.Date;

/**
 * User: willzyx
 * Date: 7/19/12 - 1:44 AM
 */
public final class LinkToOriginReviewJsonConversions {
    private LinkToOriginReviewJsonConversions() {
    }

    public static LinkToOriginReview fromJson(final JSONObject originReview) {
        return new LinkToOriginReview() {
            @Override
            public String originReviewId() {
                return originReview.optString(LinkToOriginReviewAttributes.ORIGIN_REVIEW_ID);
            }

            @Override
            public Date linkMountAt() {
                return new Date(originReview.optLong(LinkToOriginReviewAttributes.LINK_MOUNT_AT) * 1000);
            }

            @Override
            public Date linkExpireAt() {
                return new Date(originReview.optLong(LinkToOriginReviewAttributes.LINK_EXPIRE_AT) * 1000);
            }
        };
    }

    public static JSONObject toJson(LinkToOriginReview link) {
        try {
            return new JSONObject().
                    put(LinkToOriginReviewAttributes.ORIGIN_REVIEW_ID, link.originReviewId()).
                    put(LinkToOriginReviewAttributes.LINK_MOUNT_AT, link.linkMountAt().getTime() / 1000).
                    put(LinkToOriginReviewAttributes.LINK_EXPIRE_AT, link.linkExpireAt().getTime() / 1000);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toJsonString(LinkToOriginReview link) {
        return toJson(link).toString();
    }
}

