package com.linx.lio;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

class PlaceOrderRequest {
    private final NSU nsu;
    private final List<Product> productList;

    PlaceOrderRequest(@NotNull NSU nsu , @NotNull final List<Product> productList) {
        this.nsu = nsu;
        this.productList = productList;
    }

    final NSU getNsu() {
        return nsu;
    }

    final List<Product> getProductList() {
        return productList;
    }

    static PlaceOrderRequest fromJSONObject(@NotNull final JSONObject jsonObject) throws JSONException {
        final NSU nsu = NSU.fromJSONObject(jsonObject);

        final JSONArray jsonArray = jsonObject.getJSONArray("items");
        final int length = jsonArray.length();

        final List<Product> productList = new ArrayList<Product>(length);

        for (int i = 0; i < length; ++i) {
            productList.add(Product.fromJSONObject(jsonArray.getJSONObject(i)));
        }

        return new PlaceOrderRequest(nsu, productList);
    }
}