package cn.joyway.joywaybeacon;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Locale;

import cn.joyway.lib.ConvertEx;
import cn.joyway.lib.bluetooth.BT;
import cn.joyway.lib.bluetooth.Beacon;

public class Adapter_DeviceList extends BaseAdapter {

    Context _context;
    final Activity_Main _mainActivity;
    private final LayoutInflater _inflater;
    ArrayList<String> _deviceMacs = new ArrayList<>();

    public Adapter_DeviceList(Context context, Activity_Main mainActivity) {
        _context = context;
        _mainActivity = mainActivity;
        _inflater = LayoutInflater.from(context);
    }

    public void addDevice(Beacon beacon) {
        if (!_deviceMacs.contains(beacon._mac)) {
            _deviceMacs.add(beacon._mac);
        }else{
            Log.d("JoywayBeacon", "已经添加过，不再添加！");
        }
    }

    public void removeDevice(String mac) {
        _deviceMacs.remove(mac);
    }

    @Override
    public int getCount() {
        return _deviceMacs.size();
    }

    @Override
    public Object getItem(int position) {
        if (position < 0 || position >= _deviceMacs.size())
            return null;
        String mac = _deviceMacs.get(position);
        return BT.getBeacon(mac);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final class ViewHolder{

            //basic info

            public RelativeLayout rlBasicInfo;
            public ImageView ivBasic_typeIcon;
            public TextView tvBasic_Name;
            public TextView tvBasic_Mac;
            public TextView tvBasic_Model;
            public TextView tvBasic_Rssi;
            public TextView tvBasic_TxInterval;
            public Button bnBasic_Connect;

            //iBeacon info

            public RelativeLayout rlIBeaconInfo;
            public TextView tvIBeacon_UUID;
            public TextView tvIBeacon_Major;
            public TextView tvIBeacon_Minor;
            public TextView tvIBeacon_RssiAtOneMeter;

            //Eddystone info
/*
            public RelativeLayout rlEddystoneInfo;
            public TextView tvEddystone_NamespaceID;
            public TextView tvEddystone_InstanceID;
            public TextView tvEddystone_URL;
            public TextView tvEddystone_TLM_temperature;
            public TextView tvEddystone_TLM_batteryPercent;
*/
            //HT DATA

            public RelativeLayout rlHTData;
            public TextView tvHTData_Temperature;
            public TextView tvHTData_Humidity;

            //PTA data
            public RelativeLayout rlPTAData;
            public TextView tvPTAData_AirPressure;
            public TextView tvPTAData_Altitude;

            //噪音值

            public RelativeLayout rlDecibelInfo;
            public TextView tvDecibel;
            public TextView tvDevibelVoltage;
        }

        //region 准备 holder 对象
        ViewHolder holder;
        if (convertView == null) {

            holder = new ViewHolder();
            convertView = _inflater.inflate(R.layout.device_list_item, null);

            //basic info
            holder.rlBasicInfo = convertView.findViewById(R.id.rl_basic_info);
            holder.ivBasic_typeIcon = convertView.findViewById(R.id.iv_basic_type_icon);
            holder.tvBasic_Name = convertView.findViewById(R.id.tv_basic_name);
            holder.tvBasic_Mac = convertView.findViewById(R.id.tv_basic_mac);
            holder.tvBasic_Model = convertView.findViewById(R.id.tv_basic_model);
            holder.tvBasic_Rssi = convertView.findViewById(R.id.tv_basic_rssi);
            holder.tvBasic_TxInterval = convertView.findViewById(R.id.tv_basic_txInterval);
            holder.bnBasic_Connect = convertView.findViewById(R.id.bn_basic_connect);

            //ibeacon info
            holder.rlIBeaconInfo = convertView.findViewById(R.id.rl_ibeacon_info);
            holder.tvIBeacon_UUID = convertView.findViewById(R.id.tv_ibeacon_uuid_value);
            holder.tvIBeacon_Major = convertView.findViewById(R.id.tv_ibeacon_major_value);
            holder.tvIBeacon_Minor = convertView.findViewById(R.id.tv_ibeacon_minor_value);
            holder.tvIBeacon_RssiAtOneMeter = convertView.findViewById(R.id.tv_ibeacon_rssi_at_one_meter_value);

            //eddystone info
            //holder._rlEddystoneInfo = convertView.findViewById(R.id.rl_edd)

            //HT info
            holder.rlHTData = convertView.findViewById(R.id.rl_ht_info);
            holder.tvHTData_Temperature = convertView.findViewById(R.id.tv_ht_temperature_value);
            holder.tvHTData_Humidity = convertView.findViewById(R.id.tv_ht_humidity_value);

            //PTA info
            holder.rlPTAData = convertView.findViewById(R.id.rl_pta_info);
            holder.tvPTAData_AirPressure = convertView.findViewById(R.id.tv_pta_air_pressure_value);
            holder.tvPTAData_Altitude = convertView.findViewById(R.id.tv_pta_altitude_value);

            //decibel info
            holder.rlDecibelInfo = convertView.findViewById(R.id.rl_decibel_info);
            holder.tvDecibel = convertView.findViewById(R.id.tv_decibel_value);
            holder.tvDevibelVoltage = convertView.findViewById(R.id.tv_decibel_voltage_value);

            //
            convertView.setTag(holder);

        }else{

            holder = (ViewHolder)convertView.getTag();

        }
        //endregion

        Beacon beacon = (Beacon) getItem(position);

        //region 用户点击CLEAR按钮删除所有ITEM，有可能这里beacon对象是NULL，导致app崩溃
        if (beacon == null) {
            convertView.setVisibility(View.INVISIBLE);//跳过后面的赋值，item就会显示默认的行内容，因此需要隐藏这个行。但是实测会出现白行的情况。
            return convertView;
        }else{
            convertView.setVisibility(View.VISIBLE);//后面给行设置内容，这里设置为可见。
        }//endregion

        //把beacon里的数据四舍五入，UI显示好看
        //beacon.roundValues();不好用，实际出来的是3个小数位

        //region 显示 Basic info
        String advName = beacon.getDeviceAdvertisingName();
        if (advName.indexOf("JOYWAY") == 0 || advName.indexOf("JWBeacon") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.ibeacon);
            holder.tvBasic_Model.setText(R.string.ibeacon_in_configure_mode);
        }
        else if (advName.indexOf("JW1400A") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1400a);
            holder.tvBasic_Model.setText(R.string.anti_lost_alarm_beacon);
        }
        else if (advName.indexOf("JW1400DA") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1400da);
            holder.tvBasic_Model.setText(R.string.alarm_while_entering_preset_range);
        }
        else if (advName.indexOf("JW1401GU") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1401gu);
            holder.tvBasic_Model.setText(R.string.gateway_report_scanned_data_via_usb_port);
        }
        else if (advName.indexOf("JW1401GW") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1401gw);
            holder.tvBasic_Model.setText(R.string.gateway_report_scanned_data_via_wifi);
        }
        else if (advName.indexOf("JW1404B") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1404b);
            holder.tvBasic_Model.setText(R.string.ibeacon_waterdrop_shape);
        }
        else if (advName.indexOf("JW1404A") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1404a);
            holder.tvBasic_Model.setText(R.string.anti_lost_alarm_beacon_waterdrop_shape);
        }
        else if (advName.indexOf("JW1405B") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1405b);
            holder.tvBasic_Model.setText(R.string.ibeacon_rectangle);
        }
        else if (advName.indexOf("JW1405A") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1405a);
            holder.tvBasic_Model.setText(R.string.anti_lost_alarm_beacon_rectangle);
        }
        else if (advName.indexOf("JW1407B") == 0 || advName.indexOf("STGBLE-") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1407b);
            holder.tvBasic_Model.setText(R.string.ibeacon_cr2477_long_life);
        }
        else if (advName.indexOf("JW1407HT") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1407ht);
            holder.tvBasic_Model.setText(R.string.bluetooth_hygrothermograph);
        }
        else if (advName.indexOf("JW1407PTA") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1407pta);
            holder.tvBasic_Model.setText(R.string.bluetooth_barometric_altitude_thermometer);
        }
        else if (advName.indexOf("JW1409B") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1409b);
            holder.tvBasic_Model.setText(R.string.ibeacon_wristband);
        }
        else if (advName.indexOf("JW1409DA") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1409da);
            holder.tvBasic_Model.setText(R.string.distance_alarm_wristband);
        }
        else if (advName.indexOf("JW-ALARM") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.anti_lost_alarm);
            holder.tvBasic_Model.setText(R.string.anti_lost_alarm);
        }
        else if (advName.indexOf("T-Sensor") == 0) {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1407ht);
            holder.tvBasic_Model.setText(R.string.bluetooth_thermometer);
        }
        else if (advName.indexOf("JW1407DM") == 0) { //噪音计
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1407dm);
            holder.tvBasic_Model.setText(R.string.bluetooth_decibel_meter);
        }
        else if (advName.indexOf("JW1602") == 0) { // 4G网关（直接插220V）
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1602g4);
            holder.tvBasic_Model.setText(R.string.ble_gateway_with_4g_network);
        }
        else if (advName.indexOf("JW1603AG") == 0) { //泰国自动门
            holder.ivBasic_typeIcon.setImageResource(R.drawable.jw1603ag);
            holder.tvBasic_Model.setText(R.string.car_house_auto_gate);
        }
        else {
            holder.ivBasic_typeIcon.setImageResource(R.drawable.unknow_device);
            holder.tvBasic_Model.setText(null);
        }

        holder.tvBasic_Name.setText(advName);
        holder.tvBasic_Mac.setText(beacon._mac);
        holder.tvBasic_Rssi.setText(String.format(Locale.getDefault(),"%d dBm", beacon.getRssiNew()));
        holder.bnBasic_Connect.setVisibility(beacon.isConnectable() ? View.VISIBLE : View.GONE);

        //region 如果广播间隔的值有效，才能显示，否则必须隐藏
        if (beacon.getInterval_ms() == BT.INVALID_TX_INTERVAL_MS) {
            holder.tvBasic_TxInterval.setText("N/A");
        }else{
            holder.tvBasic_TxInterval.setText(String.format(Locale.getDefault(), "%d ms", beacon.getInterval_ms()));
        }//endregion

        //endregion

        //region 显示额外数据（比如iBeacon，温湿度计，气压计，分贝仪）

        // iBeacon
        if (beacon._hasIBeaconData) {
            holder.tvIBeacon_UUID.setText(beacon._uuid);
            holder.tvIBeacon_Major.setText(String.valueOf(beacon._major));
            holder.tvIBeacon_Minor.setText(String.valueOf(beacon._minor));
            int rssiAtOneMeter = ConvertEx.byte_to_int_neg128_pos127(beacon._rssiAtOneMeter);
            String rssiAtOneMeterStr = String.format(Locale.getDefault(),"%d dBm", rssiAtOneMeter);
            holder.tvIBeacon_RssiAtOneMeter.setText(rssiAtOneMeterStr);
            holder.rlIBeaconInfo.setVisibility(View.VISIBLE);
        } else {
            holder.rlIBeaconInfo.setVisibility(View.GONE);
        }

        // Eddystone
        /*if (beacon._hasEddystoneData) {
            holder.tvEddystone_NamespaceID.setText(beacon._uidNamespace);
            holder.tvEddystone_InstanceID.setText(beacon._uidInstance);
            holder.tvEddystone_URL.setText(beacon._urlType + " " +beacon._url);
            holder.tvEddystone_TLM_temperature.setText("" + beacon._temperatureOfIC + "℃");
            holder.tvEddystone_TLM_batteryPercent.setText("" + beacon._batteryPercent);
            holder.rlEddystoneInfo.setVisibility(View.VISIBLE);
        } else {
            holder.rlEddystoneInfo.setVisibility(View.GONE);
        }*/

        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        // HT data
        if (beacon._hasHTData) {
            String temperature = decimalFormat.format(beacon._temperature);
            String humidity = decimalFormat.format(beacon._humidity);
            holder.tvHTData_Temperature.setText(temperature + " ℃");
            holder.tvHTData_Humidity.setText(humidity + " %RH");
            holder.rlHTData.setVisibility(View.VISIBLE);
        }else {
            holder.rlHTData.setVisibility(View.GONE);
        }

        // PTA data
        if (beacon._hasPTAData) {
            String pressure = decimalFormat.format(beacon._airPressure);
            String altitude = decimalFormat.format(beacon._humidity);
            holder.tvPTAData_AirPressure.setText(pressure + " mbar");
            holder.tvPTAData_Altitude.setText(altitude + " m");
            holder.rlPTAData.setVisibility(View.VISIBLE);
        } else {
            holder.rlPTAData.setVisibility(View.GONE);
        }

        //Decibel data
        if (beacon._hasDecibelData) {
            holder.tvDecibel.setText(String.format(Locale.getDefault(), "%d dB", beacon._decibel));
            holder.tvDevibelVoltage.setText(String.format(Locale.getDefault(),"%d mV", beacon._decibelVoltageMS));
            holder.rlDecibelInfo.setVisibility(View.VISIBLE);
        }else {
            holder.rlDecibelInfo.setVisibility(View.GONE);
        }

        //endregion




        //region 点击按钮 “CONNECT”
        holder.bnBasic_Connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] device_desc_array = {
                    _context.getString(R.string.select_device_type_ibeacon) + ": " + _context.getString(R.string.select_device_type_ibeacon_desc),
                    _context.getString(R.string.select_device_type_jw1602g4) + ": " + _context.getString(R.string.select_device_type_jw1602g4_desc),
                    _context.getString(R.string.select_device_type_jw1401gw) + ": " + _context.getString(R.string.select_device_type_jw1401gw_desc),
                    _context.getString(R.string.select_device_type_jw1401gu) + ": " + _context.getString(R.string.select_device_type_jw1401gu_desc),
                    _context.getString(R.string.select_device_type_jw1603ag) + ": " + _context.getString(R.string.select_device_type_jw1603ag_desc),
                    _context.getString(R.string.select_device_type_jw1407dm) + ": " + _context.getString(R.string.select_device_type_jw1407dm_desc),
                };

                //region 通过广播名称，决定默认选中哪一个
                String advName = beacon.getDeviceAdvertisingName();
                int defaultSelectedItemIndex = 0;
                for (int i = 0; i < device_desc_array.length; i++) {
                    String item = (String) device_desc_array[i];
                    String[] subItmes = item.split(":");
                    if (advName.indexOf(subItmes[0]) == 0) {
                        defaultSelectedItemIndex = i;
                        break;
                    }
                }//endregion 通过广播名称，决定默认选中哪一个

                final int[] selectedItemIndex = {defaultSelectedItemIndex};
                new AlertDialog.Builder(Adapter_DeviceList.this._context)
                        .setTitle(R.string.choose_device_type)
                        .setSingleChoiceItems(device_desc_array, defaultSelectedItemIndex, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectedItemIndex[0] = which;
                    }
                })
                        .setPositiveButton(R.string.choose, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                showDeviceSettingActivity(beacon._mac, (String) device_desc_array[selectedItemIndex[0]]);
                            }
                        })
                        .setNegativeButton(R.string.cancel, null)
                        .create().show();

            }
        });
        //endregion

        return convertView;
    }

    void showDeviceSettingActivity(String mac, String advName) {
        final Intent intent;


        //可配置蓝牙信标（新版本）
        if (advName.indexOf("JoywayBeacon") == 0) {
            intent = new Intent(_context, Activity_iBeacon.class);
        }
        // 不能认识的名称，就默认为新版本的可配置的信标（可以改名字的）
        else {
            intent = new Intent(_context, Activity_iBeacon.class);
        }

        //弹出输入密码的对话框
        if (intent != null) {
            //密码框控件
            EditText etPassword = new EditText(_context);

            //显示密码对话框
            new AlertDialog.Builder(_context)
                    .setTitle(R.string.device_password)
                    .setView(etPassword)
                    .setMessage(R.string.default_password_is_empty)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //输入密码后，点击“OK”，就把密码放入intent里，使用intent启动设备设置窗口
                            Activity_Main.getInstance().stopScan();//必须停止扫描，否则太消耗资源了，会被手机系统杀死
                            String password = etPassword.getText().toString().trim();
                            intent.putExtra("MAC", mac);
                            intent.putExtra("PASSWORD", password);
                            _context.startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show();
        }
    }

}
