package com.avg.zaap.crashlibrary;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.avg.zaap.crashlibrary.core.logger.CrashLogger;

/**
 * This class represents the service connection between {@link CrashReporter} and bound service.
 * <p/>
 * Created by marek.osvald on 1.7.2016.
 */
public class CrashReporterServiceConnection implements ServiceConnection, ICrashServiceCallback {

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

    private ReportData mReportData;
    private IServiceConnectionCallback mCallback;

    /**
     * Parametric constructor. Sets unique crash code, file paths to publish and service connection
     * callback to be used.
     *
     * @param reportData report data structure
     * @param callback   callback to call whenever files have been published (or when
     *                   publishing has failed)
     */
    public CrashReporterServiceConnection(ReportData reportData, IServiceConnectionCallback callback) {
        mReportData = reportData;
        mCallback = callback;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        CrashLogger.d(TAG, "onServiceConnected() called");
        final ICrashServiceCommunicator crashService = ICrashServiceCommunicator.Stub.asInterface(service);

        try {
            crashService.publishAndroidCrash(mReportData, this);
        } catch (RemoteException e) {
            CrashLogger.e(TAG, "Unable to contact remote component, original exception %s: %s");
            mCallback.onCrashPublishingFailed();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        CrashLogger.d(TAG, "onServiceDisconnected() called, component name: %s", name);
    }

    @Override
    public void onPublisherResult(int successful, int unsuccessful) throws RemoteException {
        CrashLogger.d(TAG, "Successfully published data to %d publishers out of %d", successful, CrashLib.getConfig().getPublishers().size());
        mCallback.onCrashPublished();
    }

    @Override
    public IBinder asBinder() {
        throw new UnsupportedOperationException("asBinder() not supported");
    }

}
