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


import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import ru.yandex.webmaster3.core.semantic.review_business.auto.model.HProduct;
import ru.yandex.webmaster3.core.semantic.review_business.auto.model.impl.HProductAttributes;


/**
 * User: Evgeny Zhoga (ezhoga@yandex-team.ru)
 * Date: 5/10/12
 * Time: 12:03 PM
 */
@Slf4j
public class HProductJsonConversions {
    private HProductJsonConversions() {
    }

    public static HProduct fromJson(final String json) throws JSONException {
        return new HProductOverJson(json);
    }

    public static HProduct fromJson(final JSONObject json) {
        return new HProductOverJson(json);
    }

    public static HProduct safeFromJson(final String json) {
        try {
            return fromJson(json);
        } catch (JSONException e) {
            log.error("Error while parsing HProduct from json", e);
            return null;
        }
    }

    static JSONObject toJson(final HProduct hProduct) {
        Preconditions.checkNotNull(hProduct, "Unable to write null HProduct to JSON");
        try {
            return new JSONObject().
                    putOpt(HProductAttributes.BODY_TYPE, hProduct.getBodyType()).
                    putOpt(HProductAttributes.BODY_TYPE_NAME, hProduct.getBodyTypeName()).
                    putOpt(HProductAttributes.DISPLACEMENT, hProduct.getDisplacement()).
                    putOpt(HProductAttributes.MARK, hProduct.getMark()).
                    putOpt(HProductAttributes.MODEL, hProduct.getModel()).
                    putOpt(HProductAttributes.BRAND, hProduct.getBrand()).
                    putOpt(HProductAttributes.CATEGORY, hProduct.getCategory()).
                    putOpt(HProductAttributes.CONF_COMP_TECH_ID, hProduct.getConfCompTechId()).
                    putOpt(HProductAttributes.CONF_NAME, hProduct.getConfName()).
                    putOpt(HProductAttributes.ENGINE_TYPE, hProduct.getEngineType()).
                    putOpt(HProductAttributes.FN, hProduct.getFn()).
                    putOpt(HProductAttributes.GEAR_TYPE, hProduct.getGearType()).
                    putOpt(HProductAttributes.PRODYEAR, hProduct.getProdyear()).
                    putOpt(HProductAttributes.STEERING_WHEEL, hProduct.getSteeringWheel()).
                    putOpt(HProductAttributes.TRANSMISSION, hProduct.getTransmission()).
                    putOpt(HProductAttributes.URL, hProduct.getUrl());
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

    }

    public static String toJsonString(final HProduct hProduct) {
        return toJson(hProduct).toString();
    }

    public static String safeToJsonString(final HProduct hProduct) {
        return toJsonString(hProduct);
    }
}
