package com.usai.apex.mainframe;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.ContainerSearchActivity;
import com.usai.apex.R;
import com.usai.apex.ViewPagerAdapter;
import com.usai.util.commonUtil;

/**
 * Created by bruce on 2016/11/1.
 * HomeActivity 主界面
 */

public class RootActivity extends AppCompatActivity {

    private NoScrollViewPager viewPager;
    private MenuItem menuItem;
    private BottomNavigationView bottomNavigationView;
    int selectedMenuItem;
    boolean login=false;


    Menu actionbutton;


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        actionbutton = menu;
        getMenuInflater().inflate(R.menu.quick_search,menu);
        return  true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Toast.makeText(this, "switch mode", Toast.LENGTH_SHORT).show();

                if (login && (viewPager.getCurrentItem() == 0 || viewPager.getCurrentItem() == 1)) {
                    boolean personMode = ApexTrackingApplication.get_instance().getPersonMode();
                    personMode = !personMode;
                    ApexTrackingApplication.get_instance().setPersonMode(personMode);

                    if (personMode) {
                        getSupportActionBar().setHomeAsUpIndicator(R.drawable.apexlogo_p);
                    } else {
                        getSupportActionBar().setHomeAsUpIndicator(R.drawable.apexlogo);
                    }

                    Intent intent = new Intent("com.apex.broadcast.person_mode");
                    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
                }

                break;
            case R.id.quick_search:

                Intent intent = new Intent();
                intent.setClass(RootActivity.this,ContainerSearchActivity.class);
            startActivity(intent);

//                Toast.makeText(this,"跳转至container search activity",Toast.LENGTH_LONG).show();
                break;

        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putBoolean("login",login);
    }
    BroadcastReceiver br;
    @Override
    protected void onDestroy() {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager
                .getInstance(this);
        localBroadcastManager.unregisterReceiver(br);
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!isTaskRoot()) {
            finish();
            return;
        }

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager
                .getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("Login");
        br = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                boolean blogin = intent.getBooleanExtra("state",true);
                login=blogin;

                setupViewPager(viewPager);
            }

        };
        localBroadcastManager.registerReceiver(br, intentFilter);


        setContentView(R.layout.activity_root);

        if (savedInstanceState != null) {
            login = savedInstanceState.getBoolean("login");
        }






        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowTitleEnabled(false);
        /*
        ActionBar actionBar = getSupportActionBar();
//        actionBar.setLogo(R.drawable.apexlogo);
        actionBar.setIcon(R.drawable.apexlogo);
//        actionBar.setIcon(R.drawable.ic_launcher);

//        actionBar.setDisplayUseLogoEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setHomeButtonEnabled(true);
//        actionBar.setHomeAsUpIndicator(R.drawable.ic_launcher);
//        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
*/

        viewPager = (NoScrollViewPager) findViewById(R.id.viewpager);
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);

        bottomNavigationView.setItemIconTintList(null);
//        bottomNavigationView.setItemTextColor();;
//        bottomNavigationView.getItemTextColor();

//        bottomNavigationView.setlistener

        //默认 >3 的选中效果会影响ViewPager的滑动切换时的效果，故利用反射去掉
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        actionbutton.getItem(0).setVisible(false);
                        getSupportActionBar().setHomeAsUpIndicator(R.drawable.apexlogo);
                        getSupportActionBar().setDisplayShowTitleEnabled(false);
                        switch (item.getItemId()) {
                            case R.id.item_login:

                                viewPager.setCurrentItem(0);
                                return true;

                            case R.id.item_tool:
                                viewPager.setCurrentItem(3);
                                return true;

                            case R.id.item_otool:
                                viewPager.setCurrentItem(1);
                                return true;

                            case R.id.item_home:
                                actionbutton.getItem(0).setVisible(true);
                                if (ApexTrackingApplication.get_instance().getPersonMode()) {
                                    getSupportActionBar().setHomeAsUpIndicator(R.drawable.apexlogo_p);
                                }
                                getSupportActionBar().setDisplayShowTitleEnabled(true);
                                viewPager.setCurrentItem(0);
                                return true;

                            case R.id.item_history:
                                if (ApexTrackingApplication.get_instance().getPersonMode()) {
                                    getSupportActionBar().setHomeAsUpIndicator(R.drawable.apexlogo_p);
                                }
                                viewPager.setCurrentItem(1);
                                return true;

                            case R.id.item_search:
                                viewPager.setCurrentItem(2);
                                return true;

                            case R.id.item_my:
                                viewPager.setCurrentItem(4);
                                return true;

                        }
                        return false;
                    }
                });


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                MenuItem item= bottomNavigationView.getMenu().getItem(position);

                switch (item.getItemId())
                {
                    case R.id.item_login:
                        ApexTrackingApplication.get_instance().historyactive = false;
                        ApexTrackingApplication.get_instance().homeactive = false;
                        break;

                    case R.id.item_tool:
                        ApexTrackingApplication.get_instance().historyactive = false;
                        ApexTrackingApplication.get_instance().homeactive = false;
                        break;

                    case R.id.item_otool:
                        ApexTrackingApplication.get_instance().historyactive = false;
                        ApexTrackingApplication.get_instance().homeactive = false;
                        break;

                    case R.id.item_home:
                        ApexTrackingApplication.get_instance().historyactive = false;
                        ApexTrackingApplication.get_instance().homeactive = true;

                        HomeFragment homef=(HomeFragment)((ViewPagerAdapter)viewPager.getAdapter()).getItem(position);
                        homef.checkDirty();
                        break;

                    case R.id.item_history:

                        ApexTrackingApplication.get_instance().historyactive = true;
                        ApexTrackingApplication.get_instance().homeactive = false;
                        HistoryFragment historyf=(HistoryFragment)((ViewPagerAdapter)viewPager.getAdapter()).getItem(position);
                        historyf.checkDirty();

                        break;
                    case R.id.item_search:
                        ApexTrackingApplication.get_instance().historyactive = false;
                        ApexTrackingApplication.get_instance().homeactive = false;
                        break;

                    case R.id.item_my:
                        ApexTrackingApplication.get_instance().historyactive = false;
                        ApexTrackingApplication.get_instance().homeactive = false;
                        break;
                }



//                if(viewPager.gets)
//                if (menuItem != null) {
//                    menuItem.setChecked(false);
//                } else {
//                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
//                }
//                menuItem = bottomNavigationView.getMenu().getItem(position);
//                menuItem.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });



//        viewPager.set
////        禁止ViewPager滑动
//        viewPager.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });

        setupViewPager(viewPager);


        boolean pop = checkAllPermission();
//        if(!pop)
//        {
//            if(TextUtils.isEmpty(ApexTrackingApplication.station_name))
//            {
//                Intent intent = new Intent();
//                intent.setClass(RootActivity.this,ServerSettingActivity.class);
////            startActivity(intent);
//                startActivityForResult(intent, 0);
//            }
//        }
    }
    public boolean checkAllPermission() {


        /*
        *
        *     -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!-- External storage for caching. -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- My Location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- Maps API needs OpenGL ES 2.0. -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    <!-- End of copy. -->


    <!-- Baidu Map API -->

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
        * */



        String[] permissions = {
//                Manifest.permission.CAMERA,
//                Manifest.permission.VIBRATE,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
//                Manifest.permission.RECEIVE_BOOT_COMPLETED,
//                Manifest.permission.ACCESS_NETWORK_STATE,
//                Manifest.permission.ACCESS_WIFI_STATE,
//                Manifest.permission.INTERNET,
//                Manifest.permission.ACCESS_FINE_LOCATION,
//
//                Manifest.permission.CHANGE_CONFIGURATION



        };



//        RAUtil.checkPermissions1(this,permissions);
        boolean ret = true;
//        for(String permission : permissions) {
//            boolean granted = ;
//            if (!granted) {
//                ret= false;
//            }
//        }


        return commonUtil.checkPermissions(this,permissions);

//        return ret;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {

        if (requestCode == commonUtil.MY_PERMISSIONS_REQUEST)
        {
            boolean missing=false;
            boolean request = false;
            for(int i=0;i<grantResults.length;i++)
            {

                if(grantResults[i]!= PackageManager.PERMISSION_GRANTED)
                    missing=true;
                boolean bshow= ActivityCompat.shouldShowRequestPermissionRationale(this,permissions[i]);
                if(bshow)
                    request = true;
            }

            String msg=null;
            if(request)
                msg="Apex Mobile needs some essential permissions.";
            else
                msg="Apex Mobile will quit because missing some essential permissions.\nPlease check your system setting.";

            if(missing) {
                final boolean finalRequest = request;
                new AlertDialog.Builder(this)
                        .setTitle("Warning")
                        .setMessage(msg)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                checkAllPermission();
                                if (finalRequest)
                                    checkAllPermission();
                                else
                                    finish();
                            }
                        })
//                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
//                        }
//                    })
                        .show();
            }
            else
            {
//                if(TextUtils.isEmpty(ApexTrackingApplication.station_name))
//                {
//                    Intent intent = new Intent();
//                    intent.setClass(FullScreenLoginActivity.this,ServerSettingActivity.class);
////            startActivity(intent);
//                    startActivityForResult(intent, 0);
//                }
            }
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
//            {
//               // callPhone();
//            } else
//            {
//
//
//                            new AlertDialog.Builder(this)
//                    .setTitle("Warning")
//                    .setMessage("RA Image missing essential permission")
//                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            checkAllPermission();
//                        }
//                    })
////                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
////                        @Override
////                        public void onClick(DialogInterface dialog, int which) {
////                            finish();
////                        }
////                    })
//                    .show();
//
//                // Permission Denied
//               // Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
//            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void setupViewPager(final ViewPager viewPager) {
//        TestFragment.LoginCallBack logincallback = new TestFragment.LoginCallBack() {
//            @Override
//            public void onLogin() {
//                System.out.println("login ");
//                login = true;
////                bottomNavigationView.setSelectedItemId(bottomNavigationView.getMenu().getItem(0).getItemId());
//                bottomNavigationView.getChildAt(0).setSelected(true);
//                bottomNavigationView.getMenu().clear();
////                bottomNavigationView.getMenu().
//                bottomNavigationView.inflateMenu(R.menu.navi_login);
//                BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
//                setupViewPager(viewPager);
//
//            }
//
//            @Override
//            public void onLogout() {
//                System.out.println("log out ");
//                login=false;
//
////                BottomNavigationView v;
//
////                v.getse
////                bottomNavigationView.setSelectedItemId(bottomNavigationView.getMenu().getItem(0).getItemId());
////                navigation.setSelectedItemId(navigation.getMenu().getItem(position).getItemId());
//                bottomNavigationView.getMenu().clear();
//                bottomNavigationView.inflateMenu(R.menu.navi_logout);
//                BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
//                setupViewPager(viewPager);
//            }
//        };


        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());


//        adapter.clear();

        if(login)
        {
            if(actionbutton!=null)
                actionbutton.getItem(0).setVisible(true);

            bottomNavigationView.getChildAt(0).setSelected(true);
            bottomNavigationView.getMenu().clear();
//                bottomNavigationView.getMenu().
            bottomNavigationView.inflateMenu(R.menu.navi_login);
            BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);


            HomeFragment homeFragment = new HomeFragment();
            HistoryFragment historyFragment = new HistoryFragment();
            SearchFragment searchFragment = new SearchFragment();
            ToolsFragment toolsFragment = new ToolsFragment();
            MyFragment myFragment = new MyFragment();
//            myFragment.setCallBack(new MyFragment.LogoutCallBack() {
//                @Override
//                public void onLogout() {
//
//                                    System.out.println("log out ");
//                login=false;
//
////                BottomNavigationView v;
//
////                v.getse
////                bottomNavigationView.setSelectedItemId(bottomNavigationView.getMenu().getItem(0).getItemId());
////                navigation.setSelectedItemId(navigation.getMenu().getItem(position).getItemId());
//
//                setupViewPager(viewPager);
//                }
//            });


            adapter.addFragment(homeFragment);
            adapter.addFragment(historyFragment);
            adapter.addFragment(searchFragment);
            adapter.addFragment(toolsFragment);


            adapter.addFragment(myFragment);


            ApexTrackingApplication.get_instance().homeactive = true;



//            adapter.addFragment(BaseFragment.newInstance("home"));
//            adapter.addFragment(BaseFragment.newInstance("history"));
//            adapter.addFragment(BaseFragment.newInstance("search"));
//            adapter.addFragment(BaseFragment.newInstance("tool"));
//
//            TestFragment logoutf = TestFragment.newInstance("logout");
//            logoutf.setCallBack(logincallback);
//            adapter.addFragment(logoutf);
        }
        else
        {
            ApexTrackingApplication.get_instance().homeactive = false;
            ApexTrackingApplication.get_instance().historyactive = false;
            ApexTrackingApplication.get_instance().recentactive = false;
            if(actionbutton!=null)
                actionbutton.getItem(0).setVisible(false);
            bottomNavigationView.getChildAt(0).setSelected(true);
            bottomNavigationView.getMenu().clear();
            bottomNavigationView.inflateMenu(R.menu.navi_logout);
            BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);


            LoginFragment loginFragment = new LoginFragment();
//            loginFragment.setCallBack(new LoginFragment.LoginCallBack() {
//                @Override
//                public void onLogin() {
//                System.out.println("login ");
//                login = true;
////                bottomNavigationView.setSelectedItemId(bottomNavigationView.getMenu().getItem(0).getItemId());
//
//                setupViewPager(viewPager);
//                }
//            });
//            TestFragment loginf = TestFragment.newInstance("login");
//            loginf.setCallBack(logincallback);


            adapter.addFragment(loginFragment);

//            SearchFragment searchFragment = new SearchFragment();
//            adapter.addFragment(searchFragment);

            Fragment toolsFragment = new ToolsFragment();
            adapter.addFragment(toolsFragment);
        }







//        viewPager.removeAllViews();


        viewPager.setAdapter(adapter);
    }
}