package com.ttstd.dialer.activity.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import com.tencent.mmkv.MMKV;
import com.ttstd.dialer.R;
import com.ttstd.dialer.base.mvvm.BaseMvvmActivity;
import com.ttstd.dialer.config.CommonConfig;
import com.ttstd.dialer.databinding.ActivityMainBinding;
import com.ttstd.dialer.db.app.AppInfo;
import com.ttstd.dialer.fragment.app.AppFragment;
import com.ttstd.dialer.fragment.contact.ContactFragment;
import com.ttstd.dialer.fragment.home.HomeFragment;
import com.ttstd.dialer.fragment.settings.SettingsFragment;
import com.ttstd.dialer.view.ApkPagerAdapter;
import com.ttstd.dialer.view.ScaleCircleNavigator;

import net.lucode.hackware.magicindicator.ViewPagerHelper;

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

public class MainActivity extends BaseMvvmActivity<MainViewModel, ActivityMainBinding> {
    private static final String TAG = "MainActivity";
    private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);

    private FragmentManager mFragmentManager = getSupportFragmentManager();
    //    private BaseFragmentPagerAdapter mBaseFragmentPagerAdapter;
    private ApkPagerAdapter mApkPagerAdapter;

    private List<Fragment> mFragments = new ArrayList<>();
    private SettingsFragment mSettingsFragment;
    private ContactFragment mContactFragment;
    private HomeFragment mHomeFragment;

    private int mDefaultIndex = 0;
    private int mCurrentIndex = -1;
    private int mFragmentSize = 0;

    private int APK_PER_FRAGMENT = 9;

    private ScaleCircleNavigator mScaleCircleNavigator;

    private List<AppInfo> mAppInfos;


    @Override
    public boolean setNightMode() {
        return true;
    }

    @Override
    public boolean setfitWindow() {
        return true;
    }

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

    @Override
    protected void initDataBinding() {
        mViewModel.setContext(this);
        mViewModel.setVDBinding(mViewDataBinding);
        mViewModel.setLifecycle(getLifecycleSubject());
        mViewDataBinding.setClick(new BtnClick());
    }

    @Override
    protected void initView() {
//        mBaseFragmentPagerAdapter = new BaseFragmentPagerAdapter(mFragmentManager, mFragments);
        mApkPagerAdapter = new ApkPagerAdapter(mFragmentManager);

        mScaleCircleNavigator = new ScaleCircleNavigator(this);

        if (mSettingsFragment == null) {
            mSettingsFragment = new SettingsFragment();
            mFragments.add(mSettingsFragment);
            mFragmentSize += 1;
            mDefaultIndex += 1;
        }

        boolean contactHome = mMMKV.decodeBool(CommonConfig.CONTACT_HOME_PAGE, false);
        if (!contactHome) {
            mDefaultIndex += 1;
        }
        if (mContactFragment == null) {
            mContactFragment = new ContactFragment();
            mFragments.add(mContactFragment);
            mFragmentSize += 1;
        }

        if (mHomeFragment == null) {
            mHomeFragment = new HomeFragment();
            mFragments.add(mHomeFragment);
            mFragmentSize += 1;
        }


        mScaleCircleNavigator.setCircleCount(mFragments.size());
        mScaleCircleNavigator.notifyDataSetChanged();
        mScaleCircleNavigator.setNormalCircleColor(getColor(R.color.indicator_color_normal));
        mScaleCircleNavigator.setSelectedCircleColor(getColor(R.color.indicator_color_selected));
        mScaleCircleNavigator.setCircleClickListener(new ScaleCircleNavigator.OnCircleClickListener() {
            @Override
            public void onClick(int index) {
                mViewDataBinding.viewPager.setCurrentItem(index);
            }
        });

        mViewDataBinding.viewPager.setAdapter(mApkPagerAdapter);
        mViewDataBinding.viewPager.setOffscreenPageLimit(10);
        mViewDataBinding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.e(TAG, "onPageScrolled: position = " + position);
                if (mCurrentIndex == -1 && position == 0) {
                    mViewDataBinding.viewPager.setCurrentItem(mDefaultIndex);
                    mCurrentIndex = mDefaultIndex;
                } else {
                    mCurrentIndex = position;
                }
            }

            @Override
            public void onPageSelected(int position) {
                Log.e(TAG, "onPageSelected: position = " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.e(TAG, "onPageScrollStateChanged: state = " + state);
            }
        });
        mViewDataBinding.magicIndicator.setNavigator(mScaleCircleNavigator);
        ViewPagerHelper.bind(mViewDataBinding.magicIndicator, mViewDataBinding.viewPager);
        mViewDataBinding.viewPager.setCurrentItem(mDefaultIndex);

        Log.e(TAG, "initView: mCurrentIndex = " + mCurrentIndex);
        Log.e(TAG, "initView: mDefaultIndex = " + mDefaultIndex);
        Log.e(TAG, "initView: mFragmentSize = " + mFragmentSize);

    }

    @Override
    protected void initData() {
        registerReceivers();
        mViewModel.mDesktopSortAppData.observe(this, new Observer<List<AppInfo>>() {
            @Override
            public void onChanged(List<AppInfo> appInfos) {
                mAppInfos = appInfos;
                Log.e(TAG, "onChanged: mAppInfos size = " + mAppInfos.size());
                setAppList();
            }
        });
        mViewModel.getOutsideApp();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //修补autozie fragment item大小不一致
        Log.e(TAG, "onResume: ");
        mViewModel.getOutsideApp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ");
        unregisterReceivers();
    }

    private void registerReceivers() {
        registerAppChangedReceive();
    }

    private void unregisterReceivers() {
        if (mPackageChangedReceiver != null) {
            unregisterReceiver(mPackageChangedReceiver);
        }
    }

    private PackageChangedReceiver mPackageChangedReceiver;

    private void registerAppChangedReceive() {
        if (null == mPackageChangedReceiver) {
            mPackageChangedReceiver = new PackageChangedReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");
        registerReceiver(mPackageChangedReceiver, filter);
    }

    private class PackageChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: " + intent.getAction());
        }
    }

    private void setAppList() {
        Log.e(TAG, "setAppList: mFragments size = " + mFragments.size());
        mFragments = mFragments.subList(0, mFragmentSize);
        Log.e(TAG, "setAppList: subList mFragments size = " + mFragments.size());
        int fragmentCount = (int) Math.ceil((double) mAppInfos.size() / APK_PER_FRAGMENT);
        for (int i = 0; i < fragmentCount; i++) {
            int start = i * APK_PER_FRAGMENT;
            int end = Math.min(start + APK_PER_FRAGMENT, mAppInfos.size());
            List<AppInfo> subList = new ArrayList<>(mAppInfos.subList(start, end));
            Log.e(TAG, "setAppList: subList size = " + subList.size());
//            AppFragment appFragment = AppFragment.newInstance(subList);
            AppFragment appFragment = new AppFragment(subList);
            Log.e(TAG, "setAppList: appFragment hashCode = " + appFragment.hashCode());
            appFragment.setUpdateCallback(new AppFragment.UpdateCallback() {
                @Override
                public void onUpdate() {
                    mViewModel.getOutsideApp();
                }
            });
            mFragments.add(appFragment);
            Log.e(TAG, "setAppList: add mFragments size = " + mFragments.size());
        }
        mScaleCircleNavigator.setCircleCount(mFragments.size());
        mScaleCircleNavigator.notifyDataSetChanged();

        mApkPagerAdapter.setFragments(mFragments);
        mViewDataBinding.viewPager.setCurrentItem(mCurrentIndex);
    }

    public class BtnClick {

    }
}
