package com.bokecc.livemodule.popup;

import static android.content.Context.WIFI_SERVICE;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bokecc.livemodule.R;
import com.bokecc.livemodule.utils.Permissions;
import com.bokecc.livemodule.view.DLNAController;
import com.bokecc.livemodule.view.DLNAPlayView;
import com.bokecc.projection.ProjectionDevice;
import com.bokecc.projection.ProjectionManager;
import com.bokecc.projection.ProjectionUtils;
import com.bokecc.sdk.mobile.live.util.PermissionUtils;

import org.fourthline.cling.model.meta.Device;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 20105-2021, 创盛视联数码科技（北京）有限公司
 * FileName:
 * Author: cc视频
 * Date: 2024/4/26
 * Description:
 */
public class DLNAPopupWindow extends BasePopupWindow {

    private static final String TAG = "DLNAPopupWindow";
    private TextView tvCurrentWifi;
    private ListView lvDevice;
    private ImageView iv_research;
    private ImageView iv_projection_back;
    private LinearLayout ll_select_projection_device;
    private LinearLayout ll_searching_device;
    private LinearLayout ll_not_find_device;


    private DLNAController controller;
    private List<ProjectionDevice> deviceList;

    private DeviceAdapter deviceAdapter;

    private boolean isServerConnected = false;
    private boolean isSearching = false;
    private String url;

    private String videoName;
    private long currentPosition;

    private Handler handler = new Handler(Looper.getMainLooper());
    private DLNAPlayView dlnaPlayView;


    public DLNAPopupWindow(Context context) {
        super(context, true);
    }

    @Override
    public int getContentView() {
        return R.layout.popup_dlna;
    }


    public void setVideoName(String videoName) {
        this.videoName = videoName;
        dlnaPlayView.setVideoName(videoName);
    }

    @Override
    public void init() {
        //投屏
        tvCurrentWifi = mPopContentView.findViewById(R.id.tv_current_wifi);
//        tv_projection_state = mPopContentView.findViewById(R.id.tv_projection_state);
        lvDevice = mPopContentView.findViewById(R.id.lv_device);
        deviceList = new ArrayList<>();
        deviceAdapter = new DeviceAdapter(mContext, deviceList);
        lvDevice.setAdapter(deviceAdapter);

        dlnaPlayView = mPopContentView.findViewById(R.id.dlna_play_view_con);
        iv_research = mPopContentView.findViewById(R.id.iv_research);

//        iv_plus_volume = mPopContentView.findViewById(R.id.iv_plus_volume);

//        iv_plus_volume.setOnClickListener(this);
//        iv_minus_volume = mPopContentView.findViewById(R.id.iv_minus_volume);
//        iv_minus_volume.setOnClickListener(this);
//        iv_portrait_projection = mPopContentView.findViewById(R.id.iv_portrait_projection);
//        iv_portrait_projection.setOnClickListener(this);
        iv_projection_back = mPopContentView.findViewById(R.id.iv_projection_back);
//        iv_projection_screen_back = mPopContentView.findViewById(R.id.iv_projection_screen_back);
        iv_projection_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                release();
                if (onExitListener != null) {
                    onExitListener.onExit();
                }
            }
        });
//        iv_projection_screen_back.setOnClickListener(this);
//        btn_close_projection = mPopContentView.findViewById(R.id.btn_close_projection);
//        btn_close_projection.setOnClickListener(this);
//        rl_projectioning = mPopContentView.findViewById(R.id.rl_projectioning);
        ll_select_projection_device = mPopContentView.findViewById(R.id.ll_select_projection_device);
        ll_searching_device = mPopContentView.findViewById(R.id.ll_searching_device);
        ll_not_find_device = mPopContentView.findViewById(R.id.ll_not_find_device);
//        ll_connect_projection_fail = mPopContentView.findViewById(R.id.ll_connect_projection_fail);
//        ll_projection_volume = mPopContentView.findViewById(R.id.ll_projection_volume);
//        ll_projection_screen = mPopContentView.findViewById(R.id.ll_projection_screen);

        iv_research.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSearching) {
                    toastOnUiThread("正在搜索中，请稍后");
                    return;
                }
                ll_not_find_device.setVisibility(View.GONE);
                ll_searching_device.setVisibility(View.VISIBLE);
//                ProjectionManager.getInstance().getRegistry().removeAllRemoteDevices();
                getNetworkInfo();
                if (isServerConnected) {
                    if (controller!=null){
                        controller.searchDevice();
                    }
                } else {
                    toastOnUiThread("投屏服务启动失败，请重新启动页面");
                }
            }
        });
        lvDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProjectionDevice item = (ProjectionDevice) deviceAdapter.getItem(position);
                if (ProjectionUtils.isNull(item)) {
                    return;
                }

                Device device = item.getDevice();
                if (ProjectionUtils.isNull(device)) {
                    return;
                }
//                ll_select_projection_device.setVisibility(View.GONE);
                if (controller!=null){
                    controller.selectDevice(item);
                    controller.play(url);
                }
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (controller!=null){
                            controller.seek(currentPosition);
                        }
                    }
                },1000);
                try{
                    dlnaPlayView.setDeviceName(device.getDetails().getFriendlyName());
                }catch (Exception e){
                     e.printStackTrace();
                }
                dlnaPlayView.setVisibility(View.VISIBLE);
            }
        });

        dlnaPlayView.setIsLive(false);
        dlnaPlayView.setOnPlayViewListener(new DLNAPlayView.OnPlayViewListener() {
            @Override
            public void onExit() {
                if (dlnaPlayView!=null){
                    dlnaPlayView.setVisibility(View.GONE);
                }
                dismiss();
                release();
                if (onExitListener != null) {
                    onExitListener.onExit();
                }
            }

            @Override
            public void onPause() {
                if (controller!=null){
                    controller.pause();
                }
            }

            @Override
            public void onPlay() {
                if (controller!=null){
                    controller.resume();
                }
            }

            @Override
            public void onSeek(int position) {
                Log.i(TAG,"onSeek:"+position);
                if (controller!=null){
                    controller.seek(position*1000L);
                }
            }
        });


    }

    public void setOnExitListener(OnExitListener onExitListener) {
        this.onExitListener = onExitListener;
    }

    private OnExitListener onExitListener;

    public boolean onVolumeChange(boolean up) {
        Log.i(TAG,"onVolumeChange:"+(up?"up":"down"));

        if (controller!=null&&controller.isProjecting()){
            controller.setVolume(up);
            return false;
        }
        return false;
    }

    public void setCurrentPosition(long position) {
        //ms
        this.currentPosition = position;
    }

    public void setIsLive(boolean isLive) {
        this.isLive = isLive;
        if (dlnaPlayView!=null){
            dlnaPlayView.setIsLive(isLive);
        }
        if (controller!=null){
            controller.setIsLive(isLive);
        }
    }

    public interface OnExitListener {
        void onExit();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    public void show(String url, Activity activity, View view, int gravity, int x, int y) {
        super.show(activity, view, gravity, x, y);

        Log.i(TAG, "投屏播放链接：" + url);
        this.url = url;

        createDLNA();

        getNetworkInfo();


//        Collection<ProjectionDevice> devices = ProjectionManager.getInstance().getDmrDevices();
//        ProjectionDeviceList.getInstance().setClingDeviceList(devices);
        deviceList.clear();
//        if (devices!=null){
//            deviceList.addAll(devices);
//        }
//        deviceAdapter.notifyDataSetChanged();

    }

    private void createDLNA() {
        if (controller != null) {
            controller.stop();
            controller.destroy();
            controller = null;
        }
        controller = new DLNAController(mContext, new DLNAController.DlnaEventListener() {
            @Override
            public void onServiceConnect() {
                isServerConnected = true;
                isSearching = true;
                if (controller!=null){
                    controller.searchDevice();
                }
            }

            @Override
            public void onServiceDisConnect() {
                isServerConnected = false;
                isSearching = false;
            }

            @Override
            public void onPlay(boolean success) {
//                dlnaPlayView.setVisibility(View.VISIBLE);

            }

            @Override
            public void onPause(boolean success) {

            }

            @Override
            public void onStop(boolean success) {
                toastOnUiThread("投屏断开");
                dlnaPlayView.setVisibility(View.GONE);
            }

            @Override
            public void onProgress(long progress, long max) {
                Log.i(TAG,"onProgress:progress="+progress+"&max="+max+"");
                dlnaPlayView.updateProgress((int) progress, (int) max);
            }

            @Override
            public void onChangeVolume(boolean success, int volume) {

                Log.i(TAG,"onChangeVolume:success="+success+"&volume="+volume);
            }

            @Override
            public void onSeeked(boolean success) {

                Log.i(TAG,"onSeeked:success="+success);
            }

            @Override
            public void onDeviceAdded(ProjectionDevice device) {
                if (!deviceList.contains(device)) {
                    deviceList.add(device);
                }
                ll_not_find_device.setVisibility(View.GONE);
                deviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDeviceRemoved(ProjectionDevice device) {
                deviceList.remove(device);
                deviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSearchEnd(boolean empty) {
                Log.i(TAG, "onSearchEnd:" + empty);
                isSearching = false;
                ll_searching_device.setVisibility(View.GONE);
                if (empty) {
                    ll_not_find_device.setVisibility(View.VISIBLE);
                } else {
                    ll_not_find_device.setVisibility(View.GONE);
                }
            }

            @Override
            public void onStartPlay(boolean success) {
                if (success){

                }else {

                }
            }
        });
        controller.prepare();
        controller.setIsLive(isLive);
    }


    private boolean isLive = false;
    @Override
    public void dismiss() {
        super.dismiss();
        if (controller != null) {
            controller.stop();
            controller.destroy();
            controller = null;
        }
    }

    public void release() {
        if (controller != null) {
            controller.stopSearch();
            controller.stop();
            controller.destroy();
            controller = null;
        }
        currentPosition = 0;
        handler.removeCallbacksAndMessages(null);
    }


    private void getNetworkInfo() {
        int netWorkStatus = getNetWorkStatus(mContext);
        if (netWorkStatus == 0) {
            tvCurrentWifi.setText("当前无网络连接");
        } else if (netWorkStatus == 2) {
            tvCurrentWifi.setText("当前是手机热点");
        } else {
            getConnectWifiName(mContext, new OnWIfiChangeListener() {
                @Override
                public void onWifiChange(String name, boolean isConnect) {
                    if (!TextUtils.isEmpty(name)) {
                        tvCurrentWifi.setText(String.format("当前WIFI:%s", name));
                    }
                }
            });

        }
    }


    public interface OnWIfiChangeListener {
        void onWifiChange(String name, boolean isConnect);
    }

    public static void getConnectWifiName(final Context context, final OnWIfiChangeListener onWIfiChangeListener) {
        final WeakReference<Context> weakReference = new WeakReference<>(context);
        Permissions.request((Activity) context, new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, new Permissions.Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                if (integer == PackageManager.PERMISSION_GRANTED) {
                    if (weakReference.get() != null) {
                        String ssid = null;
                        WifiManager wifiManager = (WifiManager) weakReference.get().getApplicationContext().getSystemService(WIFI_SERVICE);
                        WifiInfo wifiInfo = null;
                        if (wifiManager != null) {
                            wifiInfo = wifiManager.getConnectionInfo();
                        }
                        if (wifiInfo != null) {
                            ssid = wifiInfo.getSSID();
                            int networkId = wifiInfo.getNetworkId();
                            if (ActivityCompat.checkSelfPermission(weakReference.get(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                                List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
                                for (WifiConfiguration wifiConfiguration : configuredNetworks) {
                                    if (wifiConfiguration.networkId == networkId) {
                                        ssid = wifiConfiguration.SSID;
                                        break;
                                    }
                                }
                            }
                            if (onWIfiChangeListener != null) {
                                onWIfiChangeListener.onWifiChange(ssid, true);
                            }

                        }
                    }

                }else {
                    if (onWIfiChangeListener != null) {
                        onWIfiChangeListener.onWifiChange("未授权", true);
                    }
                }
            }
        });

    }

    public static int getNetWorkStatus(Context context) {
        int netWorkStatus = 1;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo dataInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (wifiInfo.isConnected() && dataInfo.isConnected()) {
                //wifi和移动数据同时连接
                netWorkStatus = 3;
            } else if (wifiInfo.isConnected() && !dataInfo.isConnected()) {
                //wifi已连接，移动数据断开
                netWorkStatus = 1;
            } else if (!wifiInfo.isConnected() && dataInfo.isConnected()) {
                //wifi断开 移动数据连接
                netWorkStatus = 2;
            } else {
                //wifi断开 移动数据断开
                netWorkStatus = 0;
            }
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Network[] networks = connectivityManager.getAllNetworks();
            int nets = 0;
            for (int i = 0; i < networks.length; i++) {
                NetworkInfo netInfo = connectivityManager.getNetworkInfo(networks[i]);
                if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE && !netInfo.isConnected()) {
                    nets += 1;
                }

                if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE && netInfo.isConnected()) {
                    nets += 2;
                }

                if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    nets += 4;
                }
            }

            switch (nets) {
                case 0:
                    //wifi断开 移动数据断开
                    netWorkStatus = 0;
                    Log.i("dwdemo", "wifi断开 移动数据断开");
                    break;
                case 2:
                    //wifi断开 移动数据连接
                    netWorkStatus = 2;
                    break;
                case 4:
                    //wifi已连接，移动数据断开
                    netWorkStatus = 1;
                    break;
                case 5:
                    //wifi和移动数据同时连接
                    netWorkStatus = 3;
                    break;
                default:
                    break;
            }
        }

        return netWorkStatus;
    }
}
