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

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.core.semantic.review_business.model.Social;

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

/**
 * Date: 6/11/12
 * Author: Evgeny Zhoga (ezhoga@yandex-team.ru)
 */
public class SocialJsonConversions {
    private static final Logger log = LoggerFactory.getLogger(SocialJsonConversions.class);

    private SocialJsonConversions() {
    }

    static final Function<Social, JSONObject> SOCIAL_TO_JSON =
            new Function<Social, JSONObject>() {
                @Override
                public JSONObject apply(final Social arg) {
                    return toJson(arg);
                }
            };

    static final Function<JSONObject, Social> JSON_TO_SOCIAL =
            new Function<JSONObject, Social>() {
                @Override
                public Social apply(final JSONObject arg) {
                    return fromJson(arg);
                }
            };

    public static Social fromJson(final String json) throws JSONException {
        return new SocialOverJson(json);
    }

    public static Social fromJson(final JSONObject json) {
        return new SocialOverJson(json);
    }


    static JSONObject toJson(final Social social) {
        Preconditions.checkNotNull(social, "Unable to convert null Social to JSON");
        try {
            return new JSONObject().
                    putOpt(PROVIDER, social.getProvider()).
                    putOpt(USERNAME, social.getUsername()).
                    putOpt(USERID, social.getUserId()).
                    putOpt(PROFILE_ID, social.getProfileId())
                    ;
        } catch (JSONException e) {
            LoggerFactory.getLogger(SocialJsonConversions.class).error(
                    "Unexpected JSONException", e);
            return null;
        }

    }

    public static String toJsonString(final Social social) {
        return toJsonString(social, 0);
    }

    public static String toJsonString(final Social social, final int identFactor) {
        Preconditions.checkArgument(identFactor >= 0, "identFactor should be 0 or positive!");
        try {
            if (identFactor == 0) return toJson(social).toString();
            return toJson(social).toString(identFactor);
        } catch (JSONException e) {
            log.error("Not expected JSONException", e);
            return toJsonString(social);
        }
    }
}
