<commit_before>package com.kerchin.yellownote.ui.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.internal.NavigationMenuView;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.bumptech.glide.Glide;
import com.kerchin.global.Config;
import com.kerchin.global.DateUtil;
import com.kerchin.yellownote.BuildConfig;
import com.kerchin.yellownote.R;
import com.kerchin.yellownote.base.MyOrmLiteBaseActivity;
import com.kerchin.yellownote.data.adapter.MyFragmentPagerAdapter;
import com.kerchin.yellownote.data.bean.PrimaryData;
import com.kerchin.yellownote.data.bean.ToolbarStatus;
import com.kerchin.yellownote.data.proxy.LoginService;
import com.kerchin.yellownote.data.proxy.ShareSuggestService;
import com.kerchin.yellownote.global.MyApplication;
import com.kerchin.yellownote.ui.fragment.FolderFragment;
import com.kerchin.yellownote.ui.fragment.NoteFragment;
import com.kerchin.yellownote.utilities.ClipBoardUtils;
import com.kerchin.yellownote.utilities.CropUtil;
import com.kerchin.yellownote.utilities.ImageUtil;
import com.kerchin.yellownote.utilities.PatternLockUtils;
import com.kerchin.yellownote.utilities.helper.DayNightHelper;
import com.kerchin.yellownote.utilities.helper.sql.OrmLiteHelper;
import com.tinkerpatch.sdk.TinkerPatch;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import zhy.com.highlight.HighLight;
import zj.remote.baselibrary.util.BitmapUtil;
import zj.remote.baselibrary.util.Immerge.ImmergeUtils;
import zj.remote.baselibrary.util.NormalUtils;
import zj.remote.baselibrary.util.PreferenceUtils;
import zj.remote.baselibrary.util.SystemUtils;
import zj.remote.baselibrary.util.ThreadPool.ThreadPool;
import zj.remote.baselibrary.util.Trace;
import zj.remote.baselibrary.util.ViewPagerTransform.DepthPageTransformer;

@Route(path = "/yellow/main")
public class MainActivity extends MyOrmLiteBaseActivity<OrmLiteHelper>
        implements NavigationView.OnNavigationItemSelectedListener {
    @BindView(R.id.mMainPager)
    ViewPager mMainPager;
    @BindView(R.id.mMainFab)
    FloatingActionButton mMainFab;
    @BindView(R.id.mMainNav)
    NavigationView mMainNav;
    @BindView(R.id.mMainDrawer)
    DrawerLayout mMainDrawer;
    @BindView(R.id.mMainToolbar)
    Toolbar mMainToolbar;
    @BindView(R.id.mMainAbl)
    AppBarLayout mMainAbl;
    LinearLayout mNavHeaderLiL;
    TextView mNavHeaderMainTipTxt;
    CircleImageView mNavHeaderMainImg;
    TextView msgNote, msgFolder;
    HighLight highLight;

    public boolean isHide = false;
    //    private static Long mExitTime = (long) 0;//退出时间
    private int thisPosition = 0;
    private boolean isDrawerOpen = false;
    private SearchView mSearchView;
    private MenuItem btnSearch, btnSort, btnDelete;
    private NoteFragment noteFragment;
    private FolderFragment folderFragment;
    private ActionBarDrawerToggle toggle;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    public DayNightHelper mDayNightHelper;
    private BottomSheetDialog mBottomSheetDialog;

    private static final int REQUEST_LOAD_IMAGE = 100;
    private static final int REQUEST_QRCODE = 101;
    private static final int REQUEST_IMAGE = 102;
    private static final int REQUEST_WRITE_PERMISSION = 102;
    private static final int REQUEST_CAMERA_PERMISSION = 103;

    private File savePath;
    private File userIconFile;
    private String userIconPath;
    private String versionContent, versionCode, downloadUrl;

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        Trace.d("onSaveInstanceState" + MainActivity.class.getSimpleName());
        if (highLight != null && highLight.isShowing()) highLight.remove();
//        super.onSaveInstanceState(outState);//解决getActivity()为null
    }

    @Override
    protected void doSthBeforeSetView(Bundle savedInstanceState) {
        super.doSthBeforeSetView(savedInstanceState);
        closeSliding();
        mDayNightHelper = DayNightHelper.getInstance(this);
        if (mDayNightHelper.isDay()) {
            setTheme(R.style.DayTheme);
        } else {
            setTheme(R.style.NightTheme);
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
//        Trace.e("patch APK");
        Trace.e("base APK");
        mNavHeaderLiL = (LinearLayout) mMainNav.getHeaderView(0).findViewById(R.id.mNavHeaderLiL);
        mNavHeaderMainTipTxt = (TextView) mMainNav.getHeaderView(0).findViewById(R.id.mNavHeaderMainTipTxt);
        mNavHeaderMainImg = (CircleImageView) mMainNav.getHeaderView(0).findViewById(R.id.mNavHeaderMainImg);
        LinearLayout galleryNote = (LinearLayout) mMainNav.getMenu().findItem(R.id.nav_note).getActionView();
        msgNote = (TextView) galleryNote.findViewById(R.id.msg);
        LinearLayout galleryFolder = (LinearLayout) mMainNav.getMenu().findItem(R.id.nav_folder).getActionView();
        msgFolder = (TextView) galleryFolder.findViewById(R.id.msg);
        setSupportActionBar(mMainToolbar);
        if (BuildConfig.BUILD_TYPE.equals("debug")) {
            String str = "Yellow Note Dev";
            mNavHeaderMainTipTxt.setText(str);
        }
        toggle = new ActionBarDrawerToggle(
                this, mMainDrawer, mMainToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        NavigationMenuView navigationMenuView = (NavigationMenuView) mMainNav.getChildAt(0);
        if (navigationMenuView != null) {
            navigationMenuView.setVerticalScrollBarEnabled(false);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            Trace.d("MainActivity initData null");
            noteFragment = NoteFragment.newInstance(null);
            folderFragment = FolderFragment.newInstance(null);
        } else {
            thisPosition = 0;
            Trace.d("MainActivity initData else");
//            noteFragment = (NoteFragment) getSupportFragmentManager().findFragmentByTag(NoteFragment.class.getName());
//            if (noteFragment == null) {
//                Trace.d("noteFragment null");
            noteFragment = NoteFragment.newInstance(null);
//            }
//            folderFragment = (FolderFragment) getSupportFragmentManager().findFragmentByTag(FolderFragment.class.getName());
//            if (folderFragment == null) {
//                Trace.d("folderFragment null");
            folderFragment = FolderFragment.newInstance(null);
//            }
        }
        TinkerPatch.with().fetchPatchUpdate(true);
        //userIcon
        savePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                , MyApplication.APP_MAIN_FOLDER_NAME);
        userIconPath = savePath.getAbsolutePath() + File.separator
                + PreferenceUtils.getString(Config.KEY_USER, "", MyApplication.context) + ".jpg";
        userIconFile = new File(userIconPath);

        if (NormalUtils.requestPermission(this, REQUEST_WRITE_PERMISSION, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            setUserIcon();
        }

        checkForUpdate();
        fragments.add(noteFragment);
        fragments.add(folderFragment);
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragments);
        mMainPager.setOffscreenPageLimit(fragments.size());
        mMainPager.setAdapter(adapter);
        mMainPager.setPageTransformer(true, new DepthPageTransformer());
        mMainPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position,
                                       float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                thisPosition = position;
                mMainToolbar.setTitle(position == 0 ? "笔记" : "笔记本");
//                if (mMainFab.getTag() != null && (boolean) mMainFab.getTag())//TODO 等以后按钮式召出菜单时需要设置
//                    mMainFab.callOnClick();
                if (position == 0 && btnDelete != null) {
                    //delete初始化
                    noteFragment.respondForChange();//onPageSelected
                    btnSort.setVisible(true);
                    btnDelete.setVisible(true);
                    btnSearch.setVisible(true);
                    mMainToolbar.setOnMenuItemClickListener(noteFragment.getToolbarItemClickListener());
                    mSearchView.setOnQueryTextListener(noteFragment.getQueryTextListener());

//                    if (getFragmentStatus().isDeleteMode())
//                        noteFragment.deleteViewHide();
//                    if (noteFragment.getMainStatus().isSearchMode())
//                        noteFragment.restore();
//                    if (!getFragmentStatus().isSearchMode())
                    showBtnAdd();
//                    else
//                        hideBtnAdd();
                } else if (position == 1) {
                    btnDelete.setVisible(false);
                    btnSort.setVisible(false);
                    btnSearch.setVisible(false);
                    //隐藏软键盘
                    if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (getCurrentFocus() != null)
                            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
//                    mMainToolbar.setOnMenuItemClickListener(folderFragment.getToolbarItemClickListener());
//                    mSearchView.setOnQueryTextListener(folderFragment.getQueryTextListener());
                    FolderFragment.hasRefresh = true;
                    folderFragment.respondForChange();
                    showBtnAdd();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                if (state == 0 && thisPosition == 1)
//                    mSearchView.onActionViewCollapsed();
            }
        });
    }

    @Override
    protected void initEvent(Bundle savedInstanceState) {
        super.initEvent(savedInstanceState);
        mMainNav.setNavigationItemSelectedListener(this);
        mNavHeaderMainImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NormalUtils.yellowPicPicker(MainActivity.this, REQUEST_LOAD_IMAGE);
//                Intent i = new Intent(
//                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, REQUEST_LOAD_IMAGE);
            }
        });
        mMainDrawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                toggle.onDrawerSlide(drawerView, slideOffset);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                //menu数字
                String note = PrimaryData.getInstance().getNoteSize() + "";
                String folder = PrimaryData.getInstance().getFolderSize() + "";
                msgNote.setText(note);
                msgFolder.setText(folder);
                isDrawerOpen = true;
//                btnSearch.setVisible(false);
//                btnSort.setVisible(false);
//                btnDelete.setVisible(false);
                if (PreferenceUtils.getBoolean(Config.HIGHLIGHT_NAV, true, MainActivity.this)) {
                    PreferenceUtils.putBoolean(Config.HIGHLIGHT_NAV, false, MainActivity.this);
                    //用户操作引导库
//                    highLight = new HighLight(MainActivity.this)
//                            .addHighLight(R.id.mNavHeaderMainImg, R.layout.info_nav_first, new OnRightPosCallback(55), new RectLightShape())
//                            .autoRemove(false)
//                            .enableNext()
//                            .setClickCallback(new HighLight.OnClickCallback() {
//                                @Override
//                                public void onClick() {
//                                    Toast.makeText(MainActivity.this, "clicked and show next tip view by yourself", Toast.LENGTH_SHORT).show();
//                                    highLight.next();
//                                }
//                            })
//                            .show();
                }
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager.isActive()) {
                    try {
                        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
//                mSearchView.onActionViewCollapsed();
//                noteFragment.restore();
                toggle.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isDrawerOpen = false;
//                boolean isVisible = thisPosition == 0;
//                btnSearch.setVisible(isVisible);
//                btnDelete.setVisible(isVisible);
//                btnSort.setVisible(isVisible);
                toggle.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                toggle.onDrawerStateChanged(newState);
            }
        });
        toggle.syncState();
    }

    @Override
    protected boolean initCallback(Message msg) {
        switch (msg.what) {
            case checkUpdate:
                dialog = new MaterialDialog.Builder(MainActivity.this)
                        .title("升级版本:" + versionCode)
                        .content(versionContent)
                        .positiveText("下载")
                        .backgroundColor(mDayNightHelper.getColorRes(this, DayNightHelper.COLOR_SOFT_BACKGROUND))
                        .titleColor(mDayNightHelper.getColorRes(this, DayNightHelper.COLOR_TEXT))
                        .contentColor(mDayNightHelper.getColorRes(this, DayNightHelper.COLOR_TEXT))
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                download();
                            }
                        }).show();
                break;
            case gotoQRCode:
                dialog = new MaterialDialog.Builder(mContext)
                        .title("选择识别方式")
                        .backgroundColor(mDayNightHelper.getColorRes(mContext, DayNightHelper.COLOR_SOFT_BACKGROUND))
                        .titleColor(mDayNightHelper.getColorRes(mContext, DayNightHelper.COLOR_TEXT))
                        .items("拍照识别", "图片识别")
                        .itemsColor(mDayNightHelper.getColorRes(mContext, DayNightHelper.COLOR_TEXT))
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0) {
                                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                                    startActivityForResult(intent, REQUEST_QRCODE);
                                    overridePendingTransition(R.anim.head_in, R.anim.head_out);
                                } else if (position == 1) {
                                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, REQUEST_IMAGE);
                                }
                            }
                        }).show();
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_LOAD_IMAGE && null != data) {
                final Uri selectedImage = data.getData();
                CropUtil.startCropActivity(MainActivity.this, selectedImage);
            } else if (requestCode == REQUEST_QRCODE && data != null) {
                dealQRCode(data);
            } else if (requestCode == REQUEST_IMAGE && data != null) {
                dealQRImage(data);
            } else if (requestCode == UCrop.REQUEST_CROP) {
                dealCropResult(data);
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
//        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMainToolbar.setTitle(thisPosition == 0 ? "笔记" : "笔记本");
        mMainToolbar.setTitleTextColor(getResources().getColor(R.color.white));
        if (mMainFab != null && isHide && !getFragmentStatus().isSearchMode())
            showBtnAdd();
//        if (!PreferenceUtils.getBoolean(Config.KEY_ISLOGIN, false, MainActivity.this)) {
//            Intent intent = new Intent(this, LoginActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//            finish();
//        }
    }

    private void setUserIconByNet() {
        Trace.d("setUserIconByNet");
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final AVFile file = LoginService.getUserIcon(PreferenceUtils.getString(Config.KEY_USERICON, "", MyApplication.context));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(mContext).load(file.getUrl()).into(mNavHeaderMainImg);
                        }
                    });
                } catch (AVException | FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setUserIcon() {
        if (TextUtils.isEmpty(PreferenceUtils.getString(Config.KEY_USERICON, "", MyApplication.context))) {//使用默认头像
            Trace.d("getLocalMipmap");
            mNavHeaderMainImg.setImageResource(R.mipmap.ic_face);
        } else if (userIconFile.exists()) {//本地缓存的头像文件存在
            Trace.d("getLocalBitmap");
            mNavHeaderMainImg.setImageBitmap(BitmapUtil.getLocalBitmap(userIconPath));
//            if (!MyApplication.userIcon.equals(
//                    PreferenceUtils.getString(Config.KEY_USERICON, "", MainActivity.this)))
            setUserIconByNet();
        } else//userIcon存在但是本地文件不存在 下载并保存、设置
            setUserIconByNet();<commit_msg>1.08 is over remove localBitmap<commit_after>package com.kerchin.yellownote.ui.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.internal.NavigationMenuView;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.bumptech.glide.Glide;
import com.kerchin.global.Config;
import com.kerchin.global.DateUtil;
import com.kerchin.yellownote.BuildConfig;
import com.kerchin.yellownote.R;
import com.kerchin.yellownote.base.MyOrmLiteBaseActivity;
import com.kerchin.yellownote.data.adapter.MyFragmentPagerAdapter;
import com.kerchin.yellownote.data.bean.PrimaryData;
import com.kerchin.yellownote.data.bean.ToolbarStatus;
import com.kerchin.yellownote.data.proxy.LoginService;
import com.kerchin.yellownote.data.proxy.ShareSuggestService;
import com.kerchin.yellownote.global.MyApplication;
import com.kerchin.yellownote.ui.fragment.FolderFragment;
import com.kerchin.yellownote.ui.fragment.NoteFragment;
import com.kerchin.yellownote.utilities.ClipBoardUtils;
import com.kerchin.yellownote.utilities.CropUtil;
import com.kerchin.yellownote.utilities.ImageUtil;
import com.kerchin.yellownote.utilities.PatternLockUtils;
import com.kerchin.yellownote.utilities.helper.DayNightHelper;
import com.kerchin.yellownote.utilities.helper.sql.OrmLiteHelper;
import com.tinkerpatch.sdk.TinkerPatch;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import zhy.com.highlight.HighLight;
import zj.remote.baselibrary.util.BitmapUtil;
import zj.remote.baselibrary.util.Immerge.ImmergeUtils;
import zj.remote.baselibrary.util.NormalUtils;
import zj.remote.baselibrary.util.PreferenceUtils;
import zj.remote.baselibrary.util.SystemUtils;
import zj.remote.baselibrary.util.ThreadPool.ThreadPool;
import zj.remote.baselibrary.util.Trace;
import zj.remote.baselibrary.util.ViewPagerTransform.DepthPageTransformer;

@Route(path = "/yellow/main")
public class MainActivity extends MyOrmLiteBaseActivity<OrmLiteHelper>
        implements NavigationView.OnNavigationItemSelectedListener {
    @BindView(R.id.mMainPager)
    ViewPager mMainPager;
    @BindView(R.id.mMainFab)
    FloatingActionButton mMainFab;
    @BindView(R.id.mMainNav)
    NavigationView mMainNav;
    @BindView(R.id.mMainDrawer)
    DrawerLayout mMainDrawer;
    @BindView(R.id.mMainToolbar)
    Toolbar mMainToolbar;
    @BindView(R.id.mMainAbl)
    AppBarLayout mMainAbl;
    LinearLayout mNavHeaderLiL;
    TextView mNavHeaderMainTipTxt;
    CircleImageView mNavHeaderMainImg;
    TextView msgNote, msgFolder;
    HighLight highLight;

    public boolean isHide = false;
    //    private static Long mExitTime = (long) 0;//退出时间
    private int thisPosition = 0;
    private boolean isDrawerOpen = false;
    private SearchView mSearchView;
    private MenuItem btnSearch, btnSort, btnDelete;
    private NoteFragment noteFragment;
    private FolderFragment folderFragment;
    private ActionBarDrawerToggle toggle;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    public DayNightHelper mDayNightHelper;
    private BottomSheetDialog mBottomSheetDialog;

    private static final int REQUEST_LOAD_IMAGE = 100;
    private static final int REQUEST_QRCODE = 101;
    private static final int REQUEST_IMAGE = 102;
    private static final int REQUEST_WRITE_PERMISSION = 102;
    private static final int REQUEST_CAMERA_PERMISSION = 103;

    private File savePath;
    private File userIconFile;
    private String userIconPath;
    private String versionContent, versionCode, downloadUrl;

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        Trace.d("onSaveInstanceState" + MainActivity.class.getSimpleName());
        if (highLight != null && highLight.isShowing()) highLight.remove();
//        super.onSaveInstanceState(outState);//解决getActivity()为null
    }

    @Override
    protected void doSthBeforeSetView(Bundle savedInstanceState) {
        super.doSthBeforeSetView(savedInstanceState);
        closeSliding();
        mDayNightHelper = DayNightHelper.getInstance(this);
        if (mDayNightHelper.isDay()) {
            setTheme(R.style.DayTheme);
        } else {
            setTheme(R.style.NightTheme);
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
//        Trace.e("patch APK");
        Trace.e("base APK");
        mNavHeaderLiL = (LinearLayout) mMainNav.getHeaderView(0).findViewById(R.id.mNavHeaderLiL);
        mNavHeaderMainTipTxt = (TextView) mMainNav.getHeaderView(0).findViewById(R.id.mNavHeaderMainTipTxt);
        mNavHeaderMainImg = (CircleImageView) mMainNav.getHeaderView(0).findViewById(R.id.mNavHeaderMainImg);
        LinearLayout galleryNote = (LinearLayout) mMainNav.getMenu().findItem(R.id.nav_note).getActionView();
        msgNote = (TextView) galleryNote.findViewById(R.id.msg);
        LinearLayout galleryFolder = (LinearLayout) mMainNav.getMenu().findItem(R.id.nav_folder).getActionView();
        msgFolder = (TextView) galleryFolder.findViewById(R.id.msg);
        setSupportActionBar(mMainToolbar);
        if (BuildConfig.BUILD_TYPE.equals("debug")) {
            String str = "Yellow Note Dev";
            mNavHeaderMainTipTxt.setText(str);
        }
        toggle = new ActionBarDrawerToggle(
                this, mMainDrawer, mMainToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        NavigationMenuView navigationMenuView = (NavigationMenuView) mMainNav.getChildAt(0);
        if (navigationMenuView != null) {
            navigationMenuView.setVerticalScrollBarEnabled(false);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            Trace.d("MainActivity initData null");
            noteFragment = NoteFragment.newInstance(null);
            folderFragment = FolderFragment.newInstance(null);
        } else {
            thisPosition = 0;
            Trace.d("MainActivity initData else");
//            noteFragment = (NoteFragment) getSupportFragmentManager().findFragmentByTag(NoteFragment.class.getName());
//            if (noteFragment == null) {
//                Trace.d("noteFragment null");
            noteFragment = NoteFragment.newInstance(null);
//            }
//            folderFragment = (FolderFragment) getSupportFragmentManager().findFragmentByTag(FolderFragment.class.getName());
//            if (folderFragment == null) {
//                Trace.d("folderFragment null");
            folderFragment = FolderFragment.newInstance(null);
//            }
        }
        TinkerPatch.with().fetchPatchUpdate(true);
        //userIcon
        savePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                , MyApplication.APP_MAIN_FOLDER_NAME);
        userIconPath = savePath.getAbsolutePath() + File.separator
                + PreferenceUtils.getString(Config.KEY_USER, "", MyApplication.context) + ".jpg";
        userIconFile = new File(userIconPath);

        if (NormalUtils.requestPermission(this, REQUEST_WRITE_PERMISSION, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            setUserIcon();
        }

        checkForUpdate();
        fragments.add(noteFragment);
        fragments.add(folderFragment);
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragments);
        mMainPager.setOffscreenPageLimit(fragments.size());
        mMainPager.setAdapter(adapter);
        mMainPager.setPageTransformer(true, new DepthPageTransformer());
        mMainPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position,
                                       float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                thisPosition = position;
                mMainToolbar.setTitle(position == 0 ? "笔记" : "笔记本");
//                if (mMainFab.getTag() != null && (boolean) mMainFab.getTag())//TODO 等以后按钮式召出菜单时需要设置
//                    mMainFab.callOnClick();
                if (position == 0 && btnDelete != null) {
                    //delete初始化
                    noteFragment.respondForChange();//onPageSelected
                    btnSort.setVisible(true);
                    btnDelete.setVisible(true);
                    btnSearch.setVisible(true);
                    mMainToolbar.setOnMenuItemClickListener(noteFragment.getToolbarItemClickListener());
                    mSearchView.setOnQueryTextListener(noteFragment.getQueryTextListener());

//                    if (getFragmentStatus().isDeleteMode())
//                        noteFragment.deleteViewHide();
//                    if (noteFragment.getMainStatus().isSearchMode())
//                        noteFragment.restore();
//                    if (!getFragmentStatus().isSearchMode())
                    showBtnAdd();
//                    else
//                        hideBtnAdd();
                } else if (position == 1) {
                    btnDelete.setVisible(false);
                    btnSort.setVisible(false);
                    btnSearch.setVisible(false);
                    //隐藏软键盘
                    if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (getCurrentFocus() != null)
                            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
//                    mMainToolbar.setOnMenuItemClickListener(folderFragment.getToolbarItemClickListener());
//                    mSearchView.setOnQueryTextListener(folderFragment.getQueryTextListener());
                    FolderFragment.hasRefresh = true;
                    folderFragment.respondForChange();
                    showBtnAdd();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                if (state == 0 && thisPosition == 1)
//                    mSearchView.onActionViewCollapsed();
            }
        });
    }

    @Override
    protected void initEvent(Bundle savedInstanceState) {
        super.initEvent(savedInstanceState);
        mMainNav.setNavigationItemSelectedListener(this);
        mNavHeaderMainImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NormalUtils.yellowPicPicker(MainActivity.this, REQUEST_LOAD_IMAGE);
//                Intent i = new Intent(
//                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, REQUEST_LOAD_IMAGE);
            }
        });
        mMainDrawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                toggle.onDrawerSlide(drawerView, slideOffset);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                //menu数字
                String note = PrimaryData.getInstance().getNoteSize() + "";
                String folder = PrimaryData.getInstance().getFolderSize() + "";
                msgNote.setText(note);
                msgFolder.setText(folder);
                isDrawerOpen = true;
//                btnSearch.setVisible(false);
//                btnSort.setVisible(false);
//                btnDelete.setVisible(false);
                if (PreferenceUtils.getBoolean(Config.HIGHLIGHT_NAV, true, MainActivity.this)) {
                    PreferenceUtils.putBoolean(Config.HIGHLIGHT_NAV, false, MainActivity.this);
                    //用户操作引导库
//                    highLight = new HighLight(MainActivity.this)
//                            .addHighLight(R.id.mNavHeaderMainImg, R.layout.info_nav_first, new OnRightPosCallback(55), new RectLightShape())
//                            .autoRemove(false)
//                            .enableNext()
//                            .setClickCallback(new HighLight.OnClickCallback() {
//                                @Override
//                                public void onClick() {
//                                    Toast.makeText(MainActivity.this, "clicked and show next tip view by yourself", Toast.LENGTH_SHORT).show();
//                                    highLight.next();
//                                }
//                            })
//                            .show();
                }
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager.isActive()) {
                    try {
                        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
//                mSearchView.onActionViewCollapsed();
//                noteFragment.restore();
                toggle.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isDrawerOpen = false;
//                boolean isVisible = thisPosition == 0;
//                btnSearch.setVisible(isVisible);
//                btnDelete.setVisible(isVisible);
//                btnSort.setVisible(isVisible);
                toggle.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                toggle.onDrawerStateChanged(newState);
            }
        });
        toggle.syncState();
    }

    @Override
    protected boolean initCallback(Message msg) {
        switch (msg.what) {
            case checkUpdate:
                dialog = new MaterialDialog.Builder(MainActivity.this)
                        .title("升级版本:" + versionCode)
                        .content(versionContent)
                        .positiveText("下载")
                        .backgroundColor(mDayNightHelper.getColorRes(this, DayNightHelper.COLOR_SOFT_BACKGROUND))
                        .titleColor(mDayNightHelper.getColorRes(this, DayNightHelper.COLOR_TEXT))
                        .contentColor(mDayNightHelper.getColorRes(this, DayNightHelper.COLOR_TEXT))
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                download();
                            }
                        }).show();
                break;
            case gotoQRCode:
                dialog = new MaterialDialog.Builder(mContext)
                        .title("选择识别方式")
                        .backgroundColor(mDayNightHelper.getColorRes(mContext, DayNightHelper.COLOR_SOFT_BACKGROUND))
                        .titleColor(mDayNightHelper.getColorRes(mContext, DayNightHelper.COLOR_TEXT))
                        .items("拍照识别", "图片识别")
                        .itemsColor(mDayNightHelper.getColorRes(mContext, DayNightHelper.COLOR_TEXT))
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0) {
                                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                                    startActivityForResult(intent, REQUEST_QRCODE);
                                    overridePendingTransition(R.anim.head_in, R.anim.head_out);
                                } else if (position == 1) {
                                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, REQUEST_IMAGE);
                                }
                            }
                        }).show();
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_LOAD_IMAGE && null != data) {
                final Uri selectedImage = data.getData();
                CropUtil.startCropActivity(MainActivity.this, selectedImage);
            } else if (requestCode == REQUEST_QRCODE && data != null) {
                dealQRCode(data);
            } else if (requestCode == REQUEST_IMAGE && data != null) {
                dealQRImage(data);
            } else if (requestCode == UCrop.REQUEST_CROP) {
                dealCropResult(data);
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
//        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMainToolbar.setTitle(thisPosition == 0 ? "笔记" : "笔记本");
        mMainToolbar.setTitleTextColor(getResources().getColor(R.color.white));
        if (mMainFab != null && isHide && !getFragmentStatus().isSearchMode())
            showBtnAdd();
//        if (!PreferenceUtils.getBoolean(Config.KEY_ISLOGIN, false, MainActivity.this)) {
//            Intent intent = new Intent(this, LoginActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//            finish();
//        }
    }

    private void setUserIconByNet() {
        Trace.d("setUserIconByNet");
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final AVFile file = LoginService.getUserIcon(PreferenceUtils.getString(Config.KEY_USERICON, "", MyApplication.context));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(mContext).load(file.getUrl()).into(mNavHeaderMainImg);
                        }
                    });
                } catch (AVException | FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setUserIcon() {
        if (TextUtils.isEmpty(PreferenceUtils.getString(Config.KEY_USERICON, "", MyApplication.context))) {//使用默认头像
            Trace.d("getLocalMipmap");
            mNavHeaderMainImg.setImageResource(R.mipmap.ic_face);
        }
//        else if (userIconFile.exists()) {//本地缓存的头像文件存在
//            Trace.d("getLocalBitmap");
//            mNavHeaderMainImg.setImageBitmap(BitmapUtil.getLocalBitmap(userIconPath));
////            if (!MyApplication.userIcon.equals(
////                    PreferenceUtils.getString(Config.KEY_USERICON, "", MainActivity.this)))
//            setUserIconByNet();
//        }
        else//userIcon存在但是本地文件不存在 下载并保存、设置
            setUserIconByNet();
{'fraction_non_alphanumeric': 0.09483741505905961, 'fraction_numerical': 0.0019382496465544762, 'mean_word_length': 2.238443361394181, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 28, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5034776', 'n_tokens_mistral': 11954, 'n_tokens_neox': 11474, 'n_words': 1841}