package com.avg.zaap.crashlibrary.core;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

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

/**
 * Implements {@link IServiceConnectionHelper}.
 * When new service connection is established {@link ICrashReportingServiceCallback} is called.
 * <p/>
 * Created by marek.osvald on 17. 5. 2016.
 */
public class ServiceConnectionHelper implements IServiceConnectionHelper {

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

    private ServiceConnection mConnection;
    private final ICrashReportingServiceCallback mCallback;
    private ICrashServiceCommunicator mCrashReportingService;
    private final IServiceConnectionHelperFactory mFactory;

    /**
     * Parametric constructor. Sets the callback, uses the default dependency factory.
     *
     * @param callback crash reporting service callback
     */
    public ServiceConnectionHelper(ICrashReportingServiceCallback callback) {
        this(callback, new ServiceConnectionHelperFactory());
    }

    /**
     * Parametric constructor. Sets the callback and dependency factory to be used.
     *
     * @param callback crash reporting service callback
     * @param factory  dependency factory to be used
     */
    public ServiceConnectionHelper(ICrashReportingServiceCallback callback, IServiceConnectionHelperFactory factory) {
        mCallback = callback;
        mFactory = factory;
    }

    public void startServiceConnectionThread(final Context context) {
        mFactory.getThread(new Runnable() {
            @Override
            public void run() {
                final Intent mIntent = mFactory.getIntent(context, CrashReportingService.class);

                mConnection = new ServiceConnection() {

                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        CrashLogger.d(TAG, "onServiceConnected in Exception Handler");
                        mCrashReportingService = ICrashServiceCommunicator.Stub.asInterface(service);
                        mCallback.onServiceConnected(mCrashReportingService);
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        CrashLogger.d(TAG, "onServiceDisconnected in Exception Handler");
                    }
                };

                context.bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
            }
        }).start();
    }

}
