package org.iotivity.onboardingtool;

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

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

import java.util.ArrayList;

public class ProvisionAuthWildcardAceAndPairwisingHandler implements OCObtDeviceStatusHandler {

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

    private OnBoardingActivity activity;

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

    @Override
    public void handler(final OCUuid uuid, int status) {
        String deviceId = OCUuidUtil.uuidToString(uuid);

        final String msg = (status >= 0) ?
                "Successfully provisioned auth-crypt * ACE on device " + deviceId :
                "Error provisioning auth-crypt * ACE on device " + deviceId + ", status = " + status;

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

        /* pairwising owned device with the other owned devices */
        new Thread(new Runnable() {
            public void run() {
                final ArrayList<OcfDeviceInfo> owned_devices = (ArrayList<OcfDeviceInfo>)activity.getOwnedDeviceList().clone();
                for(OcfDeviceInfo deviceInfo : owned_devices) {
                    if(!OCUuidUtil.isEqual(uuid, deviceInfo.getUuid())) {
                        final OCUuid uuidPair = deviceInfo.getUuid();
                        Log.d(TAG, "Pairing " + OCUuidUtil.uuidToString(uuid) + " and " + OCUuidUtil.uuidToString(uuidPair));

                        if (activity.getObt().provisionPairwiseCredentials(uuid, uuidPair, new ProvisionCredentialsHandler(activity)) < 0) {
                            final String msg = "Failed to provision pair-wise credentials for " + OCUuidUtil.uuidToString(uuid) + " and " + OCUuidUtil.uuidToString(uuidPair);
                            Log.d(TAG, msg);
                            activity.runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        try {
                            Thread.sleep(2500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
}
