package com.sunzee.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.sunzee.R;
import com.sunzee.adapter.WifiListAdapter;
import com.sunzee.model.AppConstants;
import com.sunzee.model.domain.WifiBean;
import com.sunzee.utils.CollectionUtils;
import com.sunzee.utils.ToastUtil;
import com.sunzee.utils.UiUtil;
import com.sunzee.utils.WifiHelper;
import com.sunzee.utils.WifiSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author whw
 * @time 2019/3/13
 * @Description wifi列表
 */
public class WifiDialog extends Dialog implements View.OnClickListener {


    private RecyclerView mRecyListWifi;
    private ProgressBar mPdWifiLoading;

    public void setListener(DialogClickListener listener) {
        this.listener = listener;
    }

    private DialogClickListener listener;

    private final Context mContext;
    private static final String TAG = "wifidialog";

    List<WifiBean> realWifiList;

    private WifiListAdapter adapter;

    private WifiBroadcastReceiver wifiReceiver;

    private int connectType = 0;//1：连接成功？ 2 正在连接（如果wifi热点列表发生变需要该字段）

    private WifiHelper mWifiHelper;
    private boolean is_password_error;
    private static final List<String> ignoreSsid = Arrays.asList("0x", "<unknown ssid>");

    public WifiDialog(@NonNull Context context) {

        super(context, R.style.DialogBgD);//加载样式
        mContext = context;
        setContentView(R.layout.wifi_list_activity);
        initView();
    }

    protected void initView() {
        mRecyListWifi = findViewById(R.id.recy_list_wifi);
        mPdWifiLoading = findViewById(R.id.pb_wifi_loading);
        realWifiList = new ArrayList<>();
        hidingProgressBar();
        initData();
        initListener();
    }

    private void initData() {
        mWifiHelper = new WifiHelper(getContext());
        //开启wifi
        mWifiHelper.openWifi();
        //开始扫描
        mWifiHelper.startScan();
        adapter = new WifiListAdapter(getContext(), realWifiList);
        mRecyListWifi.setLayoutManager(new LinearLayoutManager(getContext()));
//        binding.recyListWifi.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL));
        mRecyListWifi.setAdapter(adapter);
    }

    private void initListener() {


        adapter.setOnItemClickListener(new WifiListAdapter.onItemClickListener() {
            @Override
            public void onItemClick(View view, int postion, Object o) {
                WifiBean wifiBean = realWifiList.get(postion);

                if (wifiBean.getState().equals(AppConstants.WIFI_STATE_UNCONNECT) || wifiBean.getState().equals(AppConstants.WIFI_STATE_CONNECT)) {
                    String capabilities = realWifiList.get(postion).getCapabilities();

                    if (WifiSupport.getWifiCipher(capabilities) == WifiSupport.WifiCipherType.WIFICIPHER_NOPASS) {
                        //无需密码
                        WifiConfiguration tempConfig = WifiSupport.isExsits(wifiBean.getWifiName(), getContext());
                        if (tempConfig == null) {
                            WifiConfiguration exsits = WifiSupport.createWifiConfig(wifiBean.getWifiName(), null, WifiSupport.WifiCipherType.WIFICIPHER_NOPASS);
                            WifiSupport.addNetWork(exsits, getContext());
                        } else {
                            WifiSupport.addNetWork(tempConfig, getContext());
                        }
                    } else if (wifiBean.getState().equals(AppConstants.WIFI_STATE_CONNECT)) {
                        //已连接 显示详情和取消保存

                        showWifiDetailDialog(wifiBean.getWifiName());

                    } else {   //需要密码，弹出输入密码dialog
                        noConfigurationWifi(postion);
                    }
                }
            }
        });
    }

    /**
     * 之前没有配置wifi， 弹出输入密码界面
     *
     * @param position
     */
    private void noConfigurationWifi(int position) {
        showDialog(realWifiList.get(position).getWifiName(), realWifiList.get(position).getCapabilities());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                dismiss();
                break;
        }


    }

    @Override
    public void show() {
        super.show();
        //注册广播
        wifiReceiver = new WifiBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态广播,是否连接了一个有效路由
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        getContext().registerReceiver(wifiReceiver, filter);
    }


    @Override
    public void dismiss() {
        super.dismiss();
        getContext().unregisterReceiver(wifiReceiver);
        listener.onClickListener(0, "");
    }

    /**
     * 监听wifi状态
     * 当都没有可用连接，系统会连接已经保存的网路
     */
    public class WifiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {//wifi开关状态
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state) {
                    /**
                     * WIFI_STATE_DISABLED    WLAN已经关闭
                     * WIFI_STATE_DISABLING   WLAN正在关闭
                     * WIFI_STATE_ENABLED     WLAN已经打开
                     * WIFI_STATE_ENABLING    WLAN正在打开
                     * WIFI_STATE_UNKNOWN     未知
                     */
                    case WifiManager.WIFI_STATE_DISABLED: {
                        Log.d(TAG, "已经关闭");
//                        setSwitchState(false);
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING: {
                        Log.d(TAG, "正在关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        Log.d(TAG, "已经打开");
//                        setSwitchState(true);
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING: {
                        Log.d(TAG, "正在打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        Log.d(TAG, "未知状态");
                        break;
                    }
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {//wifi连接网络状态变化

                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                Log.d(TAG, "wifi连接网络状态变化：" + info.toString());
                if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi断开连接
                    WifiInfo connectedWifiInfo = mWifiHelper.getConnectionWifiInfo();

                    Log.i(TAG, "wifi断开连接：" + connectedWifiInfo.getSSID());
                    if (ignoreSsid.contains(connectedWifiInfo.getSSID())) {
                        return;
                    }
                    hidingProgressBar();
                    for (int i = 0; i < realWifiList.size(); i++) {//没连接上将 所有的连接状态都置为“未连接”
                        realWifiList.get(i).setState(AppConstants.WIFI_STATE_UNCONNECT);
                    }
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                    wifiErrorConnect(connectedWifiInfo.getSSID());
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                    Log.i(TAG, "wifi已连接");
                    ToastUtil.showToast(UiUtil.getStringRes(R.string.wifi_connection_successful));
                    hidingProgressBar();
                    WifiInfo connectedWifiInfo = mWifiHelper.getConnectionWifiInfo();
                    is_password_error = false;
                    connectType = 1;
                    wifiListSet(connectedWifiInfo.getSSID(), connectType);
                } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                    Log.i(TAG, "wifi正在连接");
                    WifiInfo connectedWifiInfo = mWifiHelper.getConnectionWifiInfo();
                    if (ignoreSsid.contains(connectedWifiInfo.getSSID())) {
                        return;
                    }
                    showProgressBar();
                    connectType = 2;
                    wifiListSet(connectedWifiInfo.getSSID(), connectType);
                }
            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {  //扫描结果
                Log.i(TAG, "网络列表变化了");//几秒回调一次
                wifiListChange();
            } else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {//密码错误
                int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                Log.e(TAG, "linkWifiResult：" + linkWifiResult);
                if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                    ToastUtil.showToast(UiUtil.getStringRes(R.string.wifimmcw));
                    Log.d(TAG, "wifi密码错误: ");
                }
            }

        }
    }

    /**
     * wifi连接失败，弹出输入框输入密码
     *
     * @param ssid
     */
    private void wifiErrorConnect(String ssid) {
        if (is_password_error) {
            return;
        }
        is_password_error = true;//只弹出一次
        if (CollectionUtils.isNullOrEmpty(realWifiList)) {
            return;
        }
        WifiBean wifiBean = null;
        for (int i = 0; i < realWifiList.size(); i++) {
            wifiBean = realWifiList.get(i);
            if (("\"" + wifiBean.getWifiName() + "\"").equals(ssid)) {
                Log.i(TAG, "列表存在改wifi：" + ssid);
                break;
            }
        }
    }

    /**
     * wifi列表改变
     */
    public void wifiListChange() {
        convertScanResult();
        WifiInfo connectedWifiInfo = mWifiHelper.getConnectionWifiInfo();
        wifiListSet(connectedWifiInfo.getSSID(), connectType);
    }

    /**
     * 获取wifi列表然后将bean转成自己定义的WifiBean
     */
    public void convertScanResult() {
        List<ScanResult> scanResults = mWifiHelper.getFilterScanResult();
        realWifiList.clear();
        if (!CollectionUtils.isNullOrEmpty(scanResults)) {
            for (int i = 0; i < scanResults.size(); i++) {
                WifiBean wifiBean = new WifiBean();
                ScanResult scanResult = scanResults.get(i);
                wifiBean.setWifiName(scanResult.SSID);
                wifiBean.setState(AppConstants.WIFI_STATE_UNCONNECT);   //只要获取都假设设置成未连接，真正的状态都通过广播来确定
                wifiBean.setCapabilities(scanResult.capabilities);
                wifiBean.setLevel(String.valueOf(mWifiHelper.getLevel(scanResult.level)));
                wifiBean.setScanResult(scanResult);
                realWifiList.add(wifiBean);
            }
        }
    }


    /**
     * 将"已连接"或者"正在连接"的wifi热点放置在第一个位置
     *
     * @param wifiName
     * @param type
     */
    public void wifiListSet(String wifiName, int type) {
        int index = -1;
        WifiBean wifiInfo = new WifiBean();
        if (CollectionUtils.isNullOrEmpty(realWifiList)) {
            return;
        }
        Collections.sort(realWifiList);//根据信号强度排序
        for (int i = 0; i < realWifiList.size(); i++) {
            WifiBean wifiBean = realWifiList.get(i);
            if (index == -1 && ("\"" + wifiBean.getWifiName() + "\"").equals(wifiName)) {
                index = i;
                wifiInfo.setLevel(wifiBean.getLevel());
                wifiInfo.setWifiName(wifiBean.getWifiName());
                wifiInfo.setCapabilities(wifiBean.getCapabilities());
                wifiInfo.setScanResult(wifiBean.getScanResult());
                if (type == 1) {
                    wifiInfo.setState(AppConstants.WIFI_STATE_CONNECT);
                } else {
                    wifiInfo.setState(AppConstants.WIFI_STATE_ON_CONNECTING);
                }
            }
        }
        if (index != -1) {
            realWifiList.remove(index);
            realWifiList.add(0, wifiInfo);
            adapter.notifyDataSetChanged();
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    public void showProgressBar() {
        mPdWifiLoading.setVisibility(View.VISIBLE);
    }

    public void hidingProgressBar() {
        mPdWifiLoading.setVisibility(View.GONE);
    }

    private WifiLinkDialog dialog;

    private void showDialog(String title, String capabilities) {
        dialog = new WifiLinkDialog(mContext);
        dialog.setTitle(title);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCapabilities(capabilities);
        dialog.show();
    }

    private WifiDetailDialog wifiDetailDialog;

    private void showWifiDetailDialog(String title) {
        wifiDetailDialog = new WifiDetailDialog(mContext);
        wifiDetailDialog.setTitle(title);
        wifiDetailDialog.setContent(UiUtil.getStringRes(R.string.unsav_wifi));
        wifiDetailDialog.setBtnText(UiUtil.getStringRes(R.string.unsav_wifi1));
        wifiDetailDialog.setListener(new DialogClickListener2() {
            @Override
            public void onClickListener(int type) {
                switch (type) {
                    case R.id.btn_confirm:
                        WifiInfo wifiInfo = mWifiHelper.getConnectionWifiInfo();
                        WifiHelper wifiHelper = new WifiHelper(mContext);
                        wifiHelper.removeWifiBySsid(wifiInfo.getSSID());
                        wifiHelper.startScan();
                        wifiDetailDialog.dismiss();
                        break;
                }
            }
        });
        wifiDetailDialog.show();
    }

    public interface DialogClickListener {

        void onClickListener(int type, String text);
    }

    public interface DialogClickListener2 {

        void onClickListener(int type);

    }
}
