package com.northstar.minimap;

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

import android.util.Log;

import com.northstar.minimap.beacon.IBeacon;
import com.northstar.minimap.beacon.StickNFindBluetoothBeacon;
import com.northstar.minimap.map.Map;
import com.northstar.minimap.map.Table;

public class MapBuilder {

    JSONObject JSONMapDef;

    private void addBeacons(Map JSONMap) throws JSONException {
        Log.w("JP","In beacons");
        JSONArray beacons = JSONMapDef.getJSONArray("Beacons");
        Log.w("JP","Got Array");
        for (int i = 0; i < beacons.length(); i++) {
            JSONObject JSONBeacon = beacons.getJSONObject(i);
            IBeacon beacon = new StickNFindBluetoothBeacon(i, JSONBeacon.getString("BeaconId"),
                    new Position(JSONBeacon.getDouble("X"), JSONBeacon.getDouble("Y")));
            JSONMap.addBeacon(beacon);
        }
    }

    private void addTables(Map JSONMap) throws JSONException {
        JSONArray tables = JSONMapDef.getJSONArray("Tables");
        for (int i = 0; i < tables.length(); i++) {
            JSONObject JSONTable = tables.getJSONObject(i);
            Table table = new Table(JSONTable.getInt("TablesWide"), 
                                    JSONTable.getInt("TablesTall"), 
                                    new Position(JSONTable.getDouble("X"),
                                                 JSONTable.getDouble("Y")), 
                                    JSONTable.getInt("Width"), 
                                    JSONTable.getInt("Height"));
            JSONMap.addTable(table);
        }
    }

    public Map getMap(String JSONMapString, String mapID) {
        Map JSONMap = new Map();

        Log.w("JP", "Building map");

        try {
            JSONArray maps = new JSONArray(JSONMapString);
            for (int i = 0; i < maps.length(); i++) {
                JSONObject map = maps.getJSONObject(i);
                if (mapID.equals(map.get("Id"))) {
                    this.JSONMapDef = map;
                    break;
                }
            }
            addTables(JSONMap);
            addBeacons(JSONMap);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.w("JP", "Failed");
        }

        return JSONMap;
    }
}

@@ -682,32 +682,293 @@
 tJSONObject(i);%0A
+%0A            int number = i;%0A%0A            // Attempt to parse DeviceLabel as a number.  Use index as a fallback.%0A            try %7B%0A                number = Integer.parseInt(JSONBeacon.getString(%22DeviceLabel%22));%0A            %7D catch (NumberFormatException e) %7B%7D%0A%0A
             IBea
@@ -1010,17 +1010,22 @@
 hBeacon(
-i
+number
 , JSONBe
@@ -1040,22 +1040,22 @@
 String(%22
-Beacon
+Device
 Id%22),%0A  

Support new beacon format in JSON api endpoint.