package com.ntels.onecable.admin.common.handler;

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.util.Util;

import android.app.Activity;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BackPressCloseHandler {

    protected static final int BACK_PRESS_VALID_TIME = 2000;

    private long mBackKeyPressedTime = 0;
    private Activity mActivity;
    private Toast mToast;
    private Util mUtil = new Util();

    public BackPressCloseHandler(Activity activity) {
        this.mActivity = activity;
    }

    public void onBackPressed() {
        if (System.currentTimeMillis() > mBackKeyPressedTime + BACK_PRESS_VALID_TIME) {
            mBackKeyPressedTime = System.currentTimeMillis();
            showGuide();
            return;
        }

        if (System.currentTimeMillis() <= mBackKeyPressedTime + BACK_PRESS_VALID_TIME) {
            mActivity.finish();
        }
    }

    public void onBackPressed(String methodName) {
        if (System.currentTimeMillis() > mBackKeyPressedTime + BACK_PRESS_VALID_TIME) {
            mBackKeyPressedTime = System.currentTimeMillis();
            showGuide();
            return;
        }

        if (System.currentTimeMillis() <= mBackKeyPressedTime + BACK_PRESS_VALID_TIME) {
            runMethod(methodName);
            mToast.cancel();
        }
    }

    private void showGuide() {
        mToast= mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG823), Toast.LENGTH_SHORT);
    }

    private void runMethod(String callMethodName) {
        try {
            Method method;
            try {
                method = mActivity.getClass().getMethod(callMethodName);
            } catch (NoSuchMethodException e) {
                method = mActivity.getClass().getDeclaredMethod(callMethodName);
                method.setAccessible(true);
            }
            method.invoke(mActivity);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
