package com.autotech.we1l.items

import com.autotech.we1l.my_classes.BaseItem
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.tools.*
import org.json.JSONException
import org.json.JSONObject
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*

open class Product(id: Int, name: String?, var brandName: String?, val categoryId: Int, val brandId: Int,
                   val content: String?, val price: Double, val priceBeforeSale: Double,
                   val sku: String?, val returnPolicyDays: String?, val returnPolicyText: String?,
                   val expiryDate: Calendar, val isPharma: Boolean, val isOffer: Boolean,
                   val isNew: Boolean, val isAcceptPromotion: Boolean,
                   val noColor: ColorImage, val colors: BaseList<ColorImage>?, var isInWishList: Boolean) : BaseItem(id, name) {

    constructor(productJSON: JSONObject, categoryId: Int)
            : this(productJSON.optInt(ATTR_ID), productJSON.optString(ATTR_NAME), "", categoryId,
            productJSON.optInt(ATTR_BRAND_ID), productJSON.optString(ATTR_CONTENT),
            DecimalFormat("##.##", DecimalFormatSymbols(Locale.US)).format(productJSON.optDouble(ATTR_PRICE)).toDouble(),
            DecimalFormat("##.##", DecimalFormatSymbols(Locale.US)).format(productJSON.optDouble(ATTR_PRICE_BEFORE_SALE)).toDouble(),
            productJSON.optString(ATTR_SKU), productJSON.optString(ATTR_RETURN_POLICY_DAYS), productJSON.optString(ATTR_RETURN_POLICY_TEXT),
            try {
                Tools.utcToCalendar(productJSON.optLong(ATTR_EXP_DATE))
            } catch (e: JSONException) {
                Calendar.getInstance()
            },
            productJSON.optBoolean(ATTR_IS_PHARMA),
            productJSON.optBoolean(ATTR_IS_OFFER), productJSON.optBoolean(ATTR_IS_NEW), productJSON.optBoolean(ATTR_IS_ACCEPT_PROMOTION),
            ColorImage(productJSON.optJSONObject(ATTR_IMAGES).optJSONArray(ATTR_NO_COLOR)),
            BaseList<ColorImage>().apply {
                val colors = productJSON.optJSONObject(ATTR_IMAGES).optJSONArray(ATTR_COLOR)
                for (i in 0 until colors.length()) {
                    add(ColorImage(colors.optJSONObject(i)))
                }
            }, productJSON.optBoolean("IsLiked"))
}