package com.xg.navigation.delegates;

import android.os.Bundle;
import android.widget.Toast;

import com.xg.navigation.NavigationApplication;
import com.xg.navigation.constants.NavigationConstants;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static java.lang.System.exit;

/**
 * Created by yuanyuan on 18-1-18.
 * 继承自基础的Fragment，封装了返回方法和一些公共方法
 */

public abstract class NavigationDelegate extends BaseDelegate{

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;



    @SuppressWarnings("unchecked")
    public <T extends BaseDelegate> T getParentDelegate() {
        return (T) getParentFragment();
    }

    @Override
    public boolean onBackPressedSupport() {

        if (getFragmentManager().getBackStackEntryCount() > 1) {
            return false;
        }

        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
            getActivity().finish();
            Observable.timer(500, TimeUnit.MILLISECONDS).subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(Disposable d) {}

                @Override
                public void onNext(Long aLong) {
                    exit(0);
                }

                @Override
                public void onError(Throwable e) {}

                @Override
                public void onComplete() {}
            });
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            Toast.makeText(NavigationApplication.instance, "双击退出程序", Toast.LENGTH_LONG).show();
        }
        return true;
    }

    // for js
    public String getJsId() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            return "";
        }
        return bundle.getString("uniqueId");
    }

    // for native
    public String getNativeId() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            return "";
        }
        return bundle.getString(NavigationConstants.NativeNavigationId);
    }
}
