package com.uiui.os.fragment;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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.king.view.circleprogressview.CircleProgressView;
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.BuildConfig;
import com.uiui.os.R;
import com.uiui.os.bean.AlarmItem;
import com.uiui.os.utils.AmapManager;
import com.uiui.os.utils.ApkUtils;
import com.uiui.os.utils.AppUtil;
import com.uiui.os.utils.Utils;

import java.lang.reflect.Method;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CustomFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CustomFragment extends Fragment {
    private String TAG = CustomFragment.class.getSimpleName();

    private TextView tv_time,tv_add, tv_type, tv_status;
    private ImageView iv_pic;
    private TextView tv_temp;
    private TextView tv_battery;
    private TextView tv_location;
    private CircleProgressView cpv;
    private ConstraintLayout cl_alarm;
    private ImageView iv_charging;
    private int[] mShaderColors = new int[]{0xFFfa3db5, 0xFFF8867E, 0xFFF79F6B, 0xFFF79F6B, 0xFFF79F6B, 0xFFF8867E, 0xFFfa3db5};


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private View rootView;
    private AlarmItem alarmItem;

    public CustomFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CustomFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CustomFragment newInstance(String param1, String param2) {
        CustomFragment fragment = new CustomFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void setAlarmItem(AlarmItem item) {
        this.alarmItem = item;
        setAlarm();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        registerBatteryReceiver();
        getActivity().registerReceiver(mbatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    private void registerBatteryReceiver() {
        if (null == batteryReceiver) {
            batteryReceiver = new BatteryReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_BATTERY_LOW);
        filter.addAction(Intent.ACTION_BATTERY_OKAY);
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        getActivity().registerReceiver(batteryReceiver, filter);
    }

    BatteryReceiver batteryReceiver;

    private class BatteryReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                // 当前电量
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                // 最大电量
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
                int elec = (level * 100) / scale;
                Log.e(TAG, "electricity:=" + elec + "%");
                tv_battery.setText(elec + "%");
            } else if (Intent.ACTION_POWER_CONNECTED.equals(action)
                    || Intent.ACTION_POWER_DISCONNECTED.equals(action)
                    || Intent.ACTION_BATTERY_LOW.equals(action)
                    || Intent.ACTION_BATTERY_OKAY.equals(action)
            ) {

            }
        }
    }

    private BroadcastReceiver mbatteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "onReceive: " + action);
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
                if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
                    if (rootView != null) {
                        iv_charging.setVisibility(View.VISIBLE);
                    }
                }else {
                    if (rootView != null) {
                        iv_charging.setVisibility(View.GONE);
                    }
                }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_custom, container, false);
        initView();
        initData();
        return rootView;
    }

    private void initView() {
        tv_time = rootView.findViewById(R.id.tv_time);
        tv_add = rootView.findViewById(R.id.tv_add);
        tv_type = rootView.findViewById(R.id.tv_type);
        tv_status = rootView.findViewById(R.id.tv_status);

        iv_pic = rootView.findViewById(R.id.iv_pic);
        tv_temp = rootView.findViewById(R.id.tv_temp);
        tv_location = rootView.findViewById(R.id.tv_location);
        tv_battery = rootView.findViewById(R.id.tv_battery);
        Log.e(TAG, "initView: " + Utils.getBatteryLevel(getActivity()));
        tv_battery.setText(Utils.getBatteryLevel(getActivity()) + "%");
        cpv = rootView.findViewById(R.id.cpv);
        cpv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                killBackgroundApp();
            }
        });
        cl_alarm = rootView.findViewById(R.id.cl_alarm);
        cl_alarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApkUtils.openPackage(getActivity(), "com.alarmclock.uiui");
            }
        });
        iv_charging = rootView.findViewById(R.id.iv_charging);
        setAlarm();
        refreshMemory();
    }

    private void setAlarm() {
        if (rootView == null) return;
        if (alarmItem == null) {
            tv_time.setText("暂无闹钟");
            tv_time.setVisibility(View.GONE);
            tv_add.setVisibility(View.VISIBLE);
            tv_type.setVisibility(View.GONE);
            tv_status.setVisibility(View.GONE);
        } else {
            tv_time.setText(alarmItem.mTime);
            tv_time.setVisibility(View.VISIBLE);
            tv_add.setVisibility(View.GONE);
            tv_type.setText(alarmItem.mRepeatType);
            tv_type.setVisibility(View.VISIBLE);
            tv_status.setVisibility(View.VISIBLE);
            if (alarmItem.mActive) {
                tv_status.setText("打开");
            } else {
                tv_status.setText("关闭");
            }
        }
    }

    private void initData() {
        initAmap();
    }

    private void initAmap() {
        AMapLocationClient aMapLocationClient = AmapManager.getInstance().getLocationClient();
        aMapLocationClient.stopLocation();
        aMapLocationClient.startLocation();
        aMapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                Log.e(TAG, "onLocationChanged: " + aMapLocation);
                if (aMapLocation.getErrorCode() == 0) {
                    String city = aMapLocation.getCity();
                    getweather(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                    tv_location.setText(city);
                } else {

                }
            }
        });
    }

    private void getweather(double longitude, double latitude) {
        /**
         * 实况天气数据
         * @param location 所查询的地区，可通过该地区名称、ID、IP和经纬度进行查询经纬度格式：经度,纬度
         *                 （英文,分隔，十进制格式，北纬东经为正，南纬西经为负)
         * @param lang     (选填)多语言，可以不使用该参数，默认为简体中文
         * @param unit     (选填)单位选择，公制（m）或英制（i），默认为公制单位
         * @param listener 网络访问结果回调
         */

        QWeather.getWeatherNow(getActivity(), "" + longitude + "," + latitude, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "getWeather onError: " + e);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                Log.e(TAG, "getWeather onSuccess: " + new Gson().toJson(weatherBean));
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                    String imageName = "he" + now.getIcon();
//                    int resId = getResources().getIdentifier(imageName, "drawable", getActivity().getPackageName());
//                    iv_pic.setImageDrawable(getActivity().getDrawable(resId));
                    tv_temp.setText(now.getTemp() + "℃");
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    Log.e(TAG, "failed code: " + code);
                }
            }
        });
    }


    private void killBackgroundApp() {
        List<String> pkgList = ApkUtils.queryFilterAppList(getActivity());
        for (String pkg : pkgList) {
            if (pkg.equalsIgnoreCase(BuildConfig.APPLICATION_ID)) continue;
            killBackgroundProcesses(pkg);
        }
    }

    private void killBackgroundProcesses(String packageName) {
        ActivityManager activityManager;
        try {
            activityManager = (ActivityManager)
                    getActivity().getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.killBackgroundProcesses(packageName);
            Method forceStopPackage = activityManager.getClass()
                    .getDeclaredMethod("forceStopPackage", String.class);
//            Log.e(TAG, "killBackgroundProcesses: " + packageName);
            forceStopPackage.setAccessible(true);
            forceStopPackage.invoke(activityManager, packageName);
        } catch (Exception e) {
            Log.e(TAG, "killBackgroundProcesses: " + e.getMessage());
            e.printStackTrace();
        }
        refreshMemory();
    }

    private void refreshMemory() {
        long avail = AppUtil.getAvailMemory(getActivity());
        long total = AppUtil.getTotalMemory(getActivity());
        int x = (int) (((total - avail) / (double) total) * 100);
        cpv.setProgressColor(mShaderColors);
        cpv.showAnimation(0, x, 1000);
        float x2 = (((total - avail) / (float) total));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (batteryReceiver != null) {
            getActivity().unregisterReceiver(batteryReceiver);
        }
        if (mbatteryReceiver != null) {
            getActivity().unregisterReceiver(mbatteryReceiver);
        }
    }
}
