package org.iotivity.onboardingtool;

import android.util.Log;
import android.widget.Toast;

import org.iotivity.OCObtDeviceStatusHandler;
import org.iotivity.OCUuid;
import org.iotivity.OCUuidUtil;

public class OtmJustWorksAndAuthWildcardAceHandler implements OCObtDeviceStatusHandler {

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

    private OnBoardingActivity activity;

    public OtmJustWorksAndAuthWildcardAceHandler(OnBoardingActivity activity) {
        this.activity = activity;
    }

    @Override
    public void handler(final OCUuid uuid, int status) {
        final String deviceId = OCUuidUtil.uuidToString(uuid);
        final String msg = (status >= 0) ?
                "Successfully performed OTM on device " + deviceId :
                "Error performing ownership transfer on device " + deviceId + ", status = " + status;

        Log.d(TAG, msg);
        activity.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();
            }
        });

        if(status >= 0) {

            // provision Auth-crypt WildCard ACE to the owned device
            new Thread(new Runnable() {
                @Override
                public void run() {

                    if (activity.getObt().provisionAuthWildcardAce(uuid, new ProvisionAuthWildcardAceHandler(activity)) < 0) {
                        final String fail_msg = "Failed to provision auth-crypt * ACE for uuid " + deviceId;
                        Log.d(TAG, fail_msg);
                        activity.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(activity, fail_msg, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }).start();

            // discovery Owned devices
            /*new Thread(new Runnable() {
                public void run() {

                    activity.getOwnedDeviceList().clear();

                    if (activity.getObt().discoverOwnedDevices(new OwnedDeviceHandler(activity)) < 0) {
                        final String msg = "Failed to discover owned devices";
                        Log.d(TAG, msg);
                        activity.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }).start();*/
        }
    }
}
