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

import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
import org.json.*;
import ru.yandex.webmaster3.core.semantic.review_business.model.Author;
import ru.yandex.webmaster3.core.semantic.review_business.util.DateHelper;

import static com.google.common.collect.Iterables.isEmpty;
import static ru.yandex.webmaster3.core.semantic.review_business.model.impl.AuthorAttributes.*;

/**
 * @author Dima Schitinin <dimas@yandex-team.ru>
 */
public final class AuthorJsonConversions {
    private AuthorJsonConversions() {
    }

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

    public static Author fromJson(final String json) throws JSONException {
        return new AuthorOverJson(json);
    }

    /**
     * Use {@link #toJsonString(Author)} instead
     */
    @Deprecated
    public static JSONObject toJson(final Author author) throws JSONException {
        Preconditions.checkNotNull(author, "Unable to convert null Author to JSON");
        return new JSONObject().
                putOpt(FN, author.getFn()).
                putOpt(LOGIN, author.getLogin()).
                putOpt(DISPLAY_NAME, author.getDisplayName()).
                putOpt(SIGN_PRIVACY, author.getSignPrivacy().toString()).
                putOpt(URL, author.getUrl()).
                putOpt(EMAIL, author.getEmail()).
                putOpt(AVATAR, author.getAvatarUrl()).
                putOpt(THANKS, author.getThanksCount()).
                putOpt(AUTHPOST, author.getPostsCount()).
                putOpt(AUTHCOMMENTS, author.getCommentsCount()).
                putOpt(FRIENDS, author.getFriendsCount()).
                putOpt(KARMA, author.getKarma()).
                putOpt(REGDATE,
                        author.getRegdate() == null ?
                                null :
                                DateHelper.write(author.getRegdate())).
                putOpt(SOCIAL, isEmpty(author.getSocials()) ?
                        null :
                        new JSONArray(Collections2.transform(author.getSocials(),
                                SocialJsonConversions.SOCIAL_TO_JSON)));

    }

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

}

