package com.uas.module.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.widget.BottomNavigationView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.uas.module.common.base.BaseActivity;
import com.uas.module.common.base.BaseFragment;
import com.uas.module.common.base.ClassUtils;
import com.uas.module.common.base.IViewDelegate;
import com.uas.module.common.base.ViewManager;
import com.uas.module.common.utils.Helper.LoginHelper;
import com.uas.module.common.utils.ToastUtils;
import com.uas.module.common.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;


@Route(path = "/app/main")
public class BottomNavigationActivity extends BaseActivity {

    private NoScrollViewPager mPager;
    private List<BaseFragment> mFragments;
    private FragmentAdapter mAdapter;
    private long mExitTime = 0;
    BottomNavigationItemView messageTab;
    BottomNavigationItemView workTab;
    BottomNavigationItemView mineTab;

    Badge badge1;
    Badge badge2;
    Badge badge3;
  

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int i = item.getItemId();
            if (i == R.id.navigation_home) {
                mPager.setCurrentItem(0);
               // getSupportActionBar().setTitle("消息");
                return true;
            } else if (i == R.id.navigation_dashboard) {
                mPager.setCurrentItem(1);
               // getSupportActionBar().setTitle("工作");
                return true;
            } else if (i == R.id.navigation_notifications) {
                mPager.setCurrentItem(2);
               // getSupportActionBar().setTitle("我的");
                return true;
            }
            return false;
        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_navigation);
       // getSupportActionBar().setTitle("消息");
        BottomNavigationView navigation =  findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        messageTab= navigation.findViewById(R.id.navigation_home);
        workTab=navigation.findViewById(R.id.navigation_dashboard);     
        mineTab=navigation.findViewById(R.id.navigation_notifications);

       badge1=new QBadgeView(this).bindTarget(messageTab)
                .setShowShadow(true)
                .setBadgeGravity(Gravity.END|Gravity.TOP)
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {

                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                        
                    }
                })
         .setBadgeNumber(99);

        badge2=new QBadgeView(this).bindTarget(workTab)
                .setShowShadow(true)
                .setBadgeGravity(Gravity.END|Gravity.TOP)
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {

                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {

                    }
                })
                .setBadgeNumber(1);

        badge3=new QBadgeView(this).bindTarget(mineTab)
                .setShowShadow(true)
                .setBadgeGravity(Gravity.END|Gravity.TOP)
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {

                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {

                    }
                })
                .setBadgeText("");
        
        
        
        initViewPager();

        // 注册用户登录状态广播
        registerReceiver(mUserLogInOutReceiver, LoginHelper.getLogInOutActionFilter());
    }

    private void initViewPager() {
        //自动寻找的方式，目前还无法掌握Fragment加载顺序
       // mFragments = ViewManager.getInstance().getAllFragment();//这几个Fragment是主动添加到ViewManager中的
//        BaseFragment newsFragment = getNewsFragment();//主动寻找
//        BaseFragment girlsFragment = getGirlsFragment();//主动寻找
//        BaseFragment mineFragment = getMineFragment();//主动寻找
//        LogUtils.d("newsFragment:"+newsFragment+" g:"+girlsFragment+" m:"+mineFragment);
        mFragments=new ArrayList<>();
       // mFragments.add(newsFragment);
        mFragments.add(getMessageFragment());
        mFragments.add(getNewsFragment());
        mFragments.add(getMineFragment());
        mPager = findViewById(R.id.container_pager);
        mAdapter = new FragmentAdapter(getSupportFragmentManager(), mFragments);
        mPager.setPagerEnabled(false);
        mPager.setAdapter(mAdapter);
    }


    /**
     * 在News模块中寻找实现的Fragment
     *
     * @return Fragment
     */
    //工作Fragment组件
    private BaseFragment getNewsFragment() {
        BaseFragment newsFragment = null;
        List<IViewDelegate> viewDelegates = ClassUtils.getObjectsWithInterface(this, IViewDelegate.class, "com.uas.module.news");
        if (viewDelegates != null && !viewDelegates.isEmpty()) {
            newsFragment = viewDelegates.get(0).getFragment("");
        }
        return newsFragment;
    }

    //我的Fragment组件
    private BaseFragment getMineFragment() {
        BaseFragment newsFragment = null;
        List<IViewDelegate> viewDelegates = ClassUtils.getObjectsWithInterface(this, IViewDelegate.class, "com.uas.module.mine");
        if (viewDelegates != null && !viewDelegates.isEmpty()) {
            newsFragment = viewDelegates.get(0).getFragment("");
        }
        return newsFragment;
    }

    //消息Fragment组件
    private BaseFragment getMessageFragment() {
        BaseFragment newsFragment = null;
        List<IViewDelegate> viewDelegates = ClassUtils.getObjectsWithInterface(this, IViewDelegate.class, "com.uas.module.girls");
        if (viewDelegates != null && !viewDelegates.isEmpty()) {
            newsFragment = viewDelegates.get(0).getFragment("");
        }
        return newsFragment;
    }





    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int w =messageTab.getMeasuredWidth();
        badge1.setGravityOffset((int)(w*0.3),0,false);
        badge2.setGravityOffset((int)(w*0.3),0,false);
        badge3.setGravityOffset((int)(w*0.3),0,false);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //两秒之内按返回键就会退出
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtils.showShortToast(getString(R.string.app_exit_hint));
                mExitTime = System.currentTimeMillis();
            } else {
                ViewManager.getInstance().exitApp(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private BroadcastReceiver mUserLogInOutReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(LoginHelper.ACTION_LOGOUT)) {
                ARouter.getInstance().build("/home/login").navigation();
                finish();
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUserLogInOutReceiver);
    }
}
