package edu.byu.cs240.xmljson.json.creating;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.StringWriter;

import edu.byu.cs240.xmljson.model.CD;
import edu.byu.cs240.xmljson.model.Catalog;

public class JsonDomOutputExample {

	public static void run(StringWriter writer) throws Exception {

		Catalog catalog = new Catalog();

        catalog.add(new CD("Hide your heart", "Bonnie Tyler", "UK",
                "CBS Records", 9.90f, 1988));
        catalog.add(new CD("Greatest Hits", "Dolly Parton", "USA",
                "RCA", 9.90f, 1982));
        catalog.add(new CD("Still got the blues", "Gary Moore", "UK",
                "Virgin records", 10.20f, 1990));

		JSONObject catalogObj = buildCatalog(catalog);

        writer.append(catalogObj.toString(4));
		Log.i("JsonDomOutputExample", writer.toString());
	}
	
	private static JSONObject buildCatalog(Catalog catalog) throws Exception {

		JSONArray cdArr = new JSONArray();
		for (CD cd : catalog.getItems()) {
			cdArr.put(buildCD(cd));
		}

		JSONObject catalogObj = new JSONObject();
		catalogObj.put("CATALOG", cdArr);

		return catalogObj;
	}
	
	private static JSONObject buildCD(CD cd) throws Exception {

		JSONObject cdObj = new JSONObject();

		cdObj.put("TITLE", cd.getTitle());
		cdObj.put("ARTIST", cd.getArtist());
		cdObj.put("COUNTRY", cd.getCountry());
		cdObj.put("COMPANY", cd.getCompany());
		cdObj.put("PRICE", cd.getPrice());
		cdObj.put("YEAR", cd.getYear());

		return cdObj;
	}

}
