package com.uiui.os.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.alarmclock.uiui.IAlarmAidlInterface;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Unit;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;
import com.uiui.os.R;
import com.uiui.os.base.BaseActivity;
import com.uiui.os.bean.AlarmItem;
import com.uiui.os.fragment.AppListFragment;
import com.uiui.os.fragment.BaseFragmentPagerAdapter;
import com.uiui.os.fragment.CustomFragment;
import com.uiui.os.utils.AmapManager;
import com.uiui.os.utils.ApkUtils;
import com.uiui.os.view.ScaleCircleNavigator;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {
    private String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.magicIndicator)
    MagicIndicator magicIndicator;

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private BaseFragmentPagerAdapter adapter;
    private List<Fragment> fragments;
    private CustomFragment customFragment;

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

    @Override
    public void initView() {
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragments = new ArrayList<>();
        adapter = new BaseFragmentPagerAdapter(fragmentManager, fragments);
//        fragmentTransaction.add(R.id.viewPager, appListFragment);
//        fragmentTransaction.commit();
        customFragment = new CustomFragment();
        mAlarmServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.e(TAG, "onServiceConnected: ");
                mIAlarmAidlInterface = IAlarmAidlInterface.Stub.asInterface(service);
                getAlarmData();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e(TAG, "onServiceDisconnected: ");
                mIAlarmAidlInterface = null;
            }
        };
        bindAlarmService();
    }

    private void getAlarmData() {
        if (mIAlarmAidlInterface == null) {
            bindAlarmService();
            return;
        }
        try {
            String json = mIAlarmAidlInterface.getAlarm();
            Log.e(TAG, "onServiceConnected: " + json);
            if (json.equalsIgnoreCase("暂无闹钟")) {
                customFragment.setAlarmItem(null);
                return;
            }
            Type type = new TypeToken<AlarmItem>() {
            }.getType();
            AlarmItem alarmItem = new Gson().fromJson(json, type);
            customFragment.setAlarmItem(alarmItem);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private ServiceConnection mAlarmServiceConnection;
    private IAlarmAidlInterface mIAlarmAidlInterface;

    private void bindAlarmService() {
        if (mIAlarmAidlInterface == null) {
            //这是连接aidl服务的代码
            Intent intent = new Intent();
            intent.setAction("com.alarmclock.uiui.IAlarmAidlInterface");
            intent.setPackage("com.alarmclock.uiui");
            intent.setComponent(new ComponentName("com.alarmclock.uiui", "com.alarmclock.uiui.AIDLAlarmService"));
            bindService(intent, mAlarmServiceConnection, Context.BIND_AUTO_CREATE);
        } else {

        }
    }

    private final static int APP_LIST_SIZE = 12;

    @Override
    public void initData() {
        registmNewAppReceiver();
        fragments.add(customFragment);
        ArrayList<ApplicationInfo> applicationInfoList = ApkUtils.queryFilterAppInfo(this);
        int x = 0;
        for (int i = 0; i <= applicationInfoList.size(); i++) {
            if (i != 0 && i % APP_LIST_SIZE == 0) {
                AppListFragment appListFragment = new AppListFragment();
                appListFragment.setAppList(new ArrayList<>(applicationInfoList.subList(x, i)));
                fragments.add(appListFragment);
                x = i;
            } else if (i == applicationInfoList.size()) {
                AppListFragment appListFragment = new AppListFragment();
                fragments.add(appListFragment);
                appListFragment.setAppList(new ArrayList<>(applicationInfoList.subList(x, i)));
            }
        }
        viewPager.setAdapter(adapter);
        ScaleCircleNavigator scaleCircleNavigator = new ScaleCircleNavigator(this);
        scaleCircleNavigator.setCircleCount(fragments.size());
        scaleCircleNavigator.setNormalCircleColor(Color.DKGRAY);
        scaleCircleNavigator.setSelectedCircleColor(Color.LTGRAY);
        scaleCircleNavigator.setCircleClickListener(new ScaleCircleNavigator.OnCircleClickListener() {
            @Override
            public void onClick(int index) {

            }
        });
        magicIndicator.setNavigator(scaleCircleNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);
        if (fragments.size() > 1) {
            viewPager.setCurrentItem(1);
        }
    }

    private void addData() {
        List<Fragment> fragmentList = new ArrayList<>();
        ArrayList<ApplicationInfo> applicationInfoList = ApkUtils.queryFilterAppInfo(this);
        int x = 0;
        for (int i = 0; i <= applicationInfoList.size(); i++) {
            if (i != 0 && i % APP_LIST_SIZE == 0) {
                AppListFragment appListFragment = new AppListFragment();
                appListFragment.setAppList(new ArrayList<>(applicationInfoList.subList(x, i)));
                fragmentList.add(appListFragment);
                x = i;
            } else if (i == applicationInfoList.size()) {
                AppListFragment appListFragment = new AppListFragment();
                fragmentList.add(appListFragment);
                appListFragment.setAppList(new ArrayList<>(applicationInfoList.subList(x, i)));
            }
        }
        for (int i = 1; i <= fragmentList.size(); i++) {
            if (fragments.get(i) != null) {
                adapter.replaceFragment(i, fragmentList.get(i - 1));
                fragments.remove(i);
                fragments.add(i, fragmentList.get(i - 1));
            } else {
                adapter.addFragment(fragmentList.get(i - 1));
                fragments.add(fragmentList.get(i - 1));
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e(TAG, "onNewIntent: " + intent.getAction());
        String action = intent.getAction();
        if (TextUtils.isEmpty(action)) {
            return;
        }
        switch (action) {
            default:
                break;
            case Intent.ACTION_MAIN:
                viewPager.setCurrentItem(1);
                break;
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNewAppReceiver != null) {
            unregisterReceiver(mNewAppReceiver);
        }
    }

    private NewAppReceiver mNewAppReceiver;

    @Override
    protected void onResume() {
        super.onResume();
        getAlarmData();
    }

    private void registmNewAppReceiver() {
        mNewAppReceiver = new NewAppReceiver();
        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(mNewAppReceiver, filter);
    }

    class NewAppReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "onReceive: " + action);
            addData();
        }
    }
}
