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

import android.util.JsonWriter;
import android.util.Log;

import java.io.StringWriter;

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

public class JsonSerializerExample {

	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));

		JsonWriter jsonWriter = new JsonWriter(writer);

		jsonWriter.setIndent("   ");

		saveCatalog(catalog, jsonWriter);

        jsonWriter.flush();
        String output = writer.toString();
        Log.i("JsonSerializerExample", output);
	}
	
	private static void saveCatalog(Catalog catalog, JsonWriter jsonWriter) throws Exception {

		jsonWriter.beginObject();
		jsonWriter.name("CATALOG");

		jsonWriter.beginArray();
		for (CD cd : catalog.getItems()) {
			saveCD(cd, jsonWriter);
		}
		jsonWriter.endArray();

		jsonWriter.endObject();
	}
	
	private static void saveCD(CD cd, JsonWriter jsonWriter) throws Exception {

		jsonWriter.beginObject();
		jsonWriter.name("CD");

		jsonWriter.beginObject();
		jsonWriter.name("TITLE").value(cd.getTitle());
		jsonWriter.name("ARTIST").value(cd.getArtist());
		jsonWriter.name("COUNTRY").value(cd.getCountry());
		jsonWriter.name("COMPANY").value(cd.getCompany());
		jsonWriter.name("PRICE").value(cd.getPrice());
		jsonWriter.name("YEAR").value(cd.getYear());
		jsonWriter.endObject();

		jsonWriter.endObject();
	}

}
