package com.whohelp.zhrb.module.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.whohelp.zhrb.R;
import com.whohelp.zhrb.api.CallBack;
import com.whohelp.zhrb.base.BaseActivity;
import com.whohelp.zhrb.common.OnRecyclerViewItemClickListener;
import com.whohelp.zhrb.model.Theme;
import com.whohelp.zhrb.model.ThemesBean;
import com.whohelp.zhrb.model.remote.ModelGetThemeMenu;
import com.whohelp.zhrb.module.adapter.MenuLoadMoreAdapter;
import com.whohelp.zhrb.module.callback.MenuCallBack;
import com.whohelp.zhrb.module.eventbus.ThemeEvent;
import com.whohelp.zhrb.module.eventbus.TitleEvent;
import com.whohelp.zhrb.module.fragment.FistPageFragment;
import com.whohelp.zhrb.module.fragment.ThemeFragment;
import com.whohelp.zhrb.util.UpdateManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private int meunState = 0;
    private static final int STATE_FIRST = 0;
    private static final int STATE_OTHER = 1;

    @BindView(R.id.rv_main)
    RecyclerView rvMain;
    @BindView(R.id.fragment)
    FrameLayout fragment;
    @BindView(R.id.ll_main_singin)
    LinearLayout llMainSingin;
    @BindView(R.id.ll_main_collect)
    LinearLayout llMainCollect;
    @BindView(R.id.ll_main_download)
    LinearLayout llMainDownload;
    @BindView(R.id.navigation_view)
    NavigationView navigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private MenuLoadMoreAdapter menuAdapter;

    private LinearLayout mCheckLL;

    private ModelGetThemeMenu modelGetThemeMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        modelGetThemeMenu = new ModelGetThemeMenu();
        ButterKnife.bind(this);
        toolbar.setTitle("首页");
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
                R.string.drawer_open, R.string.drawer_close);
        mDrawerToggle.syncState();//初始化状态
        drawerLayout.setDrawerListener(mDrawerToggle);
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new FistPageFragment()).commit();

        loadMenu();

        initListener();
    }

    public static final String TAG_EXIT = "exit";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            boolean isExit = intent.getBooleanExtra(TAG_EXIT, false);
            if (isExit) {
                this.finish();
            }
        }
    }

    //静止,没有滚动
    public static final int SCROLL_STATE_IDLE = 0;
    //正在被外部拖拽,一般为用户正在用手指滚动
    public static final int SCROLL_STATE_DRAGGING = 1;
    //自动滚动开始
    public static final int SCROLL_STATE_SETTLING = 2;

    private void initListener() {
        //解决drawerlayout 手势关闭太灵敏(实验head部分也正常)
        rvMain.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE) {
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                } else {
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void loadMenu() {
        modelGetThemeMenu.getThemeMenu(new CallBack<ThemesBean>() {
            @Override
            public void onFailure(Throwable t) {
                Toast.makeText(MainActivity.this, "加载异常", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(ThemesBean response) {

            }

            @Override
            public void onSuccess(ThemesBean bean) {
                initAdapter(bean.getOthers());
            }
        });
    }

    private List<Theme> themes = new ArrayList<>();

    private void initAdapter(List<Theme> themes) {
        themes.add(0, new Theme(-100, "首页"));
        this.themes = themes;
        rvMain.setLayoutManager(new LinearLayoutManager(this));
        menuAdapter = new MenuLoadMoreAdapter(this, themes);
        rvMain.setAdapter(menuAdapter);
        menuAdapter.setListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                menuClick((LinearLayout) view, position);
            }
        });
        menuAdapter.setMenuCallBack(new MenuCallBack() {
            @Override
            public void callback(LinearLayout ll) {
                mCheckLL = ll;
                setCheckBg(ll, true);
                menuAdapter.setMenuCallBack(null);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TitleEvent event) {
        toolbar.setTitle(event.title);
    }

    private void menuClick(LinearLayout ll, int position) {
        setCheckBg(ll, true);
        drawerLayout.closeDrawers();
        if (position == 0) {
            meunState = STATE_FIRST;
        } else {
            meunState = STATE_OTHER;
        }
        invalidateOptionsMenu();
        toolbar.setTitle(themes.get(position).getName());
        if (position != 0) {
            EventBus.getDefault().postSticky(new ThemeEvent(themes.get(position)));
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new ThemeFragment()).commit();
        } else {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new FistPageFragment()).commit();
        }

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_colorfse:
                int currentNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
                getDelegate().setLocalNightMode(currentNightMode == Configuration.UI_MODE_NIGHT_NO
                        ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
                // 同样需要调用recreate方法使之生效
                recreate();
                break;
            case R.id.menu_setting:
                startActivity(new Intent(MainActivity.this, SettingActivity.class));
                break;
            case R.id.menu_sigin:
                new UpdateManager().checkUpdate(this, false);
                break;
            case R.id.menu_fouce:

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // 动态设置ToolBar状态
        switch (meunState) {
            case STATE_FIRST:
                menu.findItem(R.id.menu_colorfse).setVisible(true);
                int currentNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
                if (currentNightMode == Configuration.UI_MODE_NIGHT_NO) {
                    menu.findItem(R.id.menu_colorfse).setTitle("夜间模式");
                } else {
                    menu.findItem(R.id.menu_colorfse).setTitle("日间模式");
                }
                menu.findItem(R.id.menu_setting).setVisible(true);
                menu.findItem(R.id.menu_sigin).setVisible(true);
                menu.findItem(R.id.menu_fouce).setVisible(false);
                break;
            case STATE_OTHER:
                menu.findItem(R.id.menu_colorfse).setVisible(false);
                menu.findItem(R.id.menu_setting).setVisible(false);
                menu.findItem(R.id.menu_sigin).setVisible(false);
                menu.findItem(R.id.menu_fouce).setVisible(true);
                break;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    private void setCheckBg(LinearLayout ll, boolean isCheck) {
        if (isCheck) {
            if (mCheckLL != null) {
                mCheckLL.setBackgroundColor(getResources().getColor(R.color.menu_bg));
            }
            ll.setBackgroundColor(getResources().getColor(R.color.menu_bg_check));
            mCheckLL = ll;
        } else {
            ll.setBackgroundColor(getResources().getColor(R.color.menu_bg_check));
        }
    }

//    private long downloadId;
//
//    private void downApk() {
//        downLoad("http://zhstatic.zhihu.com/pkg/store/daily/zhihu-daily-zhihu-2.6.0(744)-release.apk");
//    }

//    private long downLoad(String url) {
//        Uri uri = Uri.parse(url);
//        DownloadManager.Request req = new DownloadManager.Request(uri);
//        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
//        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//        req.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "ZHRB.apk");
//        req.setTitle("知乎日报");
//        req.setMimeType("application/vnd.android.package-archive");
//        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//        downloadId = dm.enqueue(req);
//        SharedPreferencesUtils.put(this, "downloadId", downloadId);
//        return downloadId;
//    }

//    public void findFile(long downloadId) {
//        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
//        Cursor c = dm.query(query);
//        if (c != null) {
//            if (c.moveToFirst()) {
//                String fileUri = c.getString(c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
//
//            }
//            c.close();
//        }
//    }

//    public int findState(long downloadId) {
//        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
//        Cursor c = dm.query(query);
//        if (c != null && c.moveToFirst()) {
//            int status = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
//            switch (status) {
//                case DownloadManager.STATUS_PENDING:
//                    return DownloadManager.STATUS_PENDING;
//                case DownloadManager.STATUS_PAUSED:
//                    return DownloadManager.STATUS_PAUSED;
//                case DownloadManager.STATUS_RUNNING:
//                    return DownloadManager.STATUS_RUNNING;
//                case DownloadManager.STATUS_SUCCESSFUL:
//                    return DownloadManager.STATUS_SUCCESSFUL;
//                case DownloadManager.STATUS_FAILED:
//                    return DownloadManager.STATUS_FAILED;
//            }
//            if (c != null) {
//                c.close();
//            }
//        }
//        return 0;
//    }
}