package org.iotivity.onboardingtool;

import android.util.Log;

import org.iotivity.OCClientResponse;
import org.iotivity.OCResponseHandler;
import org.iotivity.OCUuidUtil;
import org.iotivity.oc.OcCborException;
import org.iotivity.oc.OcRepresentation;

public class GetDeviceNameHandler implements OCResponseHandler {

    private static final String TAG = GetDeviceNameHandler.class.getSimpleName();

    private static final String N_KEY = "n";
    private static final String DI_KEY = "di";
    private static final String PIID_KEY = "piid";
    private static final String ICV_KEY = "icv";
    private static final String DMV_KEY = "dmv";

    private OnBoardingActivity activity;
    private boolean ownedList;


    public GetDeviceNameHandler(OnBoardingActivity activity, boolean ownedList) {
        this.activity = activity;
        this.ownedList = ownedList;
    }

    @Override
    public void handler(OCClientResponse response) {
        Log.d(TAG, "Get Device Name Handler:");
        OcRepresentation rep = new OcRepresentation(response.getPayload());
        String n = null;
        String di = null;
        String piid=null, icv=null, dmv = null ;
        while (rep != null) {
            try {
                //Log.d(TAG, "Types = " + rep.getType());
                //Log.d(TAG, rep.getKey() + " = " + rep.getValue().getString());
                if (N_KEY.equals(rep.getKey())) {
                    n = rep.getString(N_KEY);
                }
                if (DI_KEY.equals(rep.getKey())) {
                    di = rep.getString(DI_KEY);
                }
                if(PIID_KEY.equals(rep.getKey())) {
                    piid = rep.getString(PIID_KEY);
                }
                if(ICV_KEY.equals(rep.getKey())) {
                    icv = rep.getString(ICV_KEY);
                }
                if(DMV_KEY.equals(rep.getKey())) {
                    dmv = rep.getString(DMV_KEY);
                }
            } catch (OcCborException e) {
                Log.e(TAG, e.getMessage());
            }
            rep = rep.getNext();
        }

        if ((di != null) && (n != null)) {

            OcfDeviceInfo device = new OcfDeviceInfo(OCUuidUtil.stringToUuid(di), n);
            device.setPiid(OCUuidUtil.stringToUuid(piid));
            device.setSpec(icv);
            device.setDataModel(dmv);

            if (ownedList) {
                activity.addOwnedDevice(device);
            } else {
                activity.addUnownedDevice(device);
            }
        }
    }
}
