package com.sunzee.ui.fragment;

import android.content.Context;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RadioButton;
import android.widget.SeekBar;

import com.orhanobut.hawk.Hawk;
import com.sunzee.R;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.MvpFragment;
import com.sunzee.model.domain.Name;
import com.sunzee.model.message.NetMessageEvent;
import com.sunzee.mvp.other.OtherPresenter;
import com.sunzee.mvp.other.OtherView;
import com.sunzee.receiver.NetworkConnectChangedReceiver;
import com.sunzee.ui.dialog.WifiDialog;

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

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 其他页界面 fragment
 * 1.4G和wifi的切换的功能
 * 2.亮度
 * 3.音量
 * 4.机器联系人
 * 5.长按退出程序
 * 6.长按重启触摸屏。
 */
public class OtherFragment extends MvpFragment<OtherPresenter> implements OtherView, SeekBar.OnSeekBarChangeListener, View.OnClickListener {

    private SeekBar mSbLight;
    private SeekBar mSbVoice;
    private AudioManager am;
    private static final String TAG = "OtherFragment";
    private RadioButton mRbMobileNetWork;
    private RadioButton mRbWifi;
    private NetworkConnectChangedReceiver receiver;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_other, container, false);
        initView(inflate);
        initEvent();
        return inflate;
    }

    private void initEvent() {
        //如果进度条发生改变
        mSbLight.setOnSeekBarChangeListener(this);
        //如果进度条发生改变
        mSbVoice.setOnSeekBarChangeListener(this);
        mRbMobileNetWork.setOnClickListener(this);
        mRbWifi.setOnClickListener(this);
    }

    private void initView(View inflate) {
        mSbLight = inflate.findViewById(R.id.sb_light);
        mSbVoice = inflate.findViewById(R.id.sb_voice);
        mRbMobileNetWork = inflate.findViewById(R.id.rb_4g);
        mRbWifi = inflate.findViewById(R.id.rb_wifi);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        //每次界面刷新都需要重新获取音量和亮度
        initSeekBar();
        //初始化选择的网络：wifi还是移动4g
        initNetwork();
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 初始化网络类型
     * 1.开启广播监听当前网络类型时
     */
    private void initNetwork() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkConnectChangedReceiver();
        getActivity().registerReceiver(receiver, filter);
        int netType = Hawk.get(Name.NET_TYPE, -1);
        if (netType == 0) {
            mRbMobileNetWork.setChecked(true);
        } else if (netType == 1) {
            mRbWifi.setChecked(true);
        }
    }


    //如果网络类型发生改变，那么就会到这里设置选中的一个方式。
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(NetMessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case wifi:
                mRbWifi.setChecked(true);
                break;
            case mobile:
                mRbMobileNetWork.setChecked(true);
                break;
        }
    }

    private WifiDialog wifiDialog;
    //避免重复触发点击事件
    private boolean isCanClick = true;

    private void showWifiDialog() {
        if (wifiDialog == null) {
            wifiDialog = new WifiDialog(this.getContext());
        }
        wifiDialog.setCanceledOnTouchOutside(true);
        wifiDialog.setListener(new WifiDialog.DialogClickListener() {
            @Override
            public void onClickListener(int type, String text) {
                int apnType = getAPNType(BaseApplication.getContext());
                Log.d(TAG, "onClickListener: apnType " + apnType);
                if (apnType == 1) {
                    Log.d(TAG, "onClickListener: wifi");
                    isCanClick = true;
                    mRbWifi.setChecked(true);

                } else if (apnType == 2 || apnType == 3) {
                    Log.d(TAG, "onClickListener: dismiss 4g");
                    isCanClick = false;
                    mRbMobileNetWork.setChecked(true);


                }
            }
        });
        wifiDialog.show();
    }

    /**
     * 获取网络状态 没有网络0：WIFI网络1：3G网络2：2G网络3
     *
     * @param context
     * @return
     */
    public int getAPNType(Context context) {
        int netType = 0;
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;// wifi
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager mTelephony = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                    && !mTelephony.isNetworkRoaming()) {
                netType = 2;// 3G
            } else {
                netType = 3;// 2G
            }
        }
        return netType;
    }

    @Override
    protected OtherPresenter createPresenter() {
        return new OtherPresenter(this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    //------------------------------------------------ seekbar 数值改变的方法重写
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.sb_light:
                //todo 测试不了，因为没有设备亮度可调。
                int seekBarProgress = seekBar.getProgress();
                changeAppBrightness(seekBarProgress);
                break;
            case R.id.sb_voice:
                am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                seekBar.setProgress(currentVolume);
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    //------------------------------------------------ seekbar 数值改变的方法重写

    /**
     * 获取系统亮度和音量，初始化。
     */
    private void initSeekBar() {
        //设置最大值音量
        am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mSbVoice.setMax(maxVolume);
        //设置当前音量
        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        mSbVoice.setProgress(currentVolume);
        //亮度
        mSbLight.setMax(255);
        try {
            int anInt = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            mSbLight.setProgress(anInt);
        } catch (Settings.SettingNotFoundException e) {
            Log.d(TAG, "initSeekBar: 获取系统亮度失败");
            e.printStackTrace();
        }
    }

    /**
     * 设置系统亮度
     *
     * @param brightness
     */
    public void changeAppBrightness(int brightness) {
        Window window = getActivity().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_4g:
                mvpPresenter.toggleWiFi(BaseApplication.getContext(), false);
                mvpPresenter.toggleMobileData(BaseApplication.getContext(), true);
                break;
            case R.id.rb_wifi:
                mvpPresenter.toggleMobileData(BaseApplication.getContext(), false);
                mvpPresenter.toggleWiFi(BaseApplication.getContext(), true);
                showWifiDialog();
                break;
        }
    }
    /**
     * 隐藏软键盘
     */
    private void hideSoftInput() {
        View v = getActivity().getCurrentFocus();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen = manager.isActive();
            if (isOpen) {
                manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

}
