package com.asreader.asr033w;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import com.asreader.asr033w.adapter.DataModel;
import com.asreader.asr033w.adapter.ListAdapter;
import com.asreader.asr033w.manager.ASR033WManager;
import com.asreader.asr033w.asr033w.ASR033W;
import com.asreader.asr033w.asr033w.ASR033WCallBack;
import com.asreader.asr033w.asr033w.Constants;
import com.asreader.asr033w.asr033w.asr033wenum.ASR033WConnectMethod;
import com.asreader.asr033w.asr033w.asr033wenum.ASR033WResultCode;
import com.asreader.asr033w.asr033w.asr033wenum.ASR033WNetworkState;
import com.asreader.asr033w.asr033w.asr033wenum.ASR033WSubCommandType;
import com.asreader.asr033w.utils.ASR033WUserConfigs;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView search;
    private TextView more;
    CustomAlertDialog dialog = null;
    private TextView ip;
    private TextView port;
    private TextView connect;
    private TextView disconnect;
    private ListView listView;
    private ListAdapter listAdapter;
    private TextView countTextView;
    private TextView totalTextView;
    private TextView startTextView;
    private TextView stopTextView;
    private TextView clearTextView;
    private TextView tcpTextView;
    private TextView mqttTextView;
    private Switch rfidSwitch;
    private Switch hidSwitch;
    private int count = 0;
    private int total = 0;
    private HashMap<String, DataModel> dataDic = new HashMap<>();
    private ASR033WUserConfigs asr033WUserConfigs;
    private Drawable tealColor;
    private Drawable grayColor;
    private AlertDialog.Builder warningDialog;
    private boolean searchStatus = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tealColor = getResources().getDrawable(R.color.red);
        grayColor = getResources().getDrawable(R.color.gray);
        asr033WUserConfigs = ASR033WUserConfigs.getInstance();
        asr033WUserConfigs.setContext(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        View view  = LayoutInflater.from(this).inflate(R.layout.action_bar_layout,null);
        getSupportActionBar().setCustomView(view,
                new ActionBar.LayoutParams(
                        ActionBar.LayoutParams.MATCH_PARENT,
                        ActionBar.LayoutParams.MATCH_PARENT,
                        Gravity.CENTER));
        search =view.findViewById(R.id.left_button);
        search.setOnClickListener(this);
        more =view.findViewById(R.id.right_button);
        more.setOnClickListener(this);
        more.setEnabled(false);
        ip = findViewById(R.id.ip_value);
        port = findViewById(R.id.port_value);
        connect = findViewById(R.id.connect);
        connect.setOnClickListener(this);
        disconnect = findViewById(R.id.disconnect);
        disconnect.setOnClickListener(this);
        listAdapter = new ListAdapter(this);
        listView = findViewById(R.id.listview);
        listView.setAdapter(listAdapter);
        countTextView = findViewById(R.id.count_title);
        totalTextView = findViewById(R.id.totol_title);
        countTextView.setText("Count:" + count);
        totalTextView.setText("Total:" + total);
        startTextView = findViewById(R.id.start_title);
        startTextView.setOnClickListener(this);
        stopTextView = findViewById(R.id.stop_title);
        stopTextView.setOnClickListener(this);
        clearTextView = findViewById(R.id.clear_title);
        clearTextView.setOnClickListener(this);
        tcpTextView = findViewById(R.id.tcp);
        tcpTextView.setOnClickListener(this);
        mqttTextView = findViewById(R.id.mqtt);
        mqttTextView.setOnClickListener(this);
        rfidSwitch = findViewById(R.id.rfid);
        rfidSwitch.setOnClickListener(this);
        hidSwitch = findViewById(R.id.hid);
        hidSwitch.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.right_button) {
            if (ASR033WUserConfigs.getInstance().getRFIDStatus()) {
                Intent intent = new Intent(MainActivity.this, MoreActivity.class);
                startActivity(intent);
            } else {
                showOpenRFIDDialog();
            }
        }else if (v.getId() == R.id.connect) {
            if(ip.getText().toString().isEmpty() ){
                SearchBuilder builder =  new SearchBuilder(MainActivity.this).setInputValue("10").setHidden(true).setCancelHidden(true);
                dialog = builder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).setTitle("Please input ip.");
                dialog.show();
                return;
            }
            if(port.getText().toString().isEmpty()){
                SearchBuilder builder =  new SearchBuilder(MainActivity.this).setInputValue("10").setHidden(true).setCancelHidden(true);
                dialog = builder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).setTitle("Please input port.");
                dialog.show();
                return;
            }
            connect(ip.getText().toString(),Integer.parseInt(port.getText().toString()));
        }else if (v.getId() == R.id.disconnect) {
            ASR033W.sharedInstance().disconnectServer();
        }else if (v.getId() == R.id.left_button){
            if (dialog != null){
                if (dialog.isShowing()){
                    dialog.dismiss();
                }
            }
            SearchBuilder builder =  new SearchBuilder(MainActivity.this).setInputValue("10");
            dialog = builder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ipItems.clear();
                    int timeOut = 10;
                    String value = builder.getInputValue();
                    try {
                        timeOut= Integer.valueOf(value);
                    } catch (Exception e){

                    }
                    searchStatus = true;
                    ASR033W.sharedInstance().setSearchDeviceTimeout(timeOut);
                    ASR033W.sharedInstance().startSearchDevice();
                    dialog.dismiss();
                    dialog = new ProgressHUDBuilder(MainActivity.this).setTitle("Searching ...");
                    dialog.show();
                }
            }).setCancelOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            }).setTitle("Search Timeout(10~60s)");
            dialog.show();
        } else if (v.getId() == R.id.start_title) {
            if (ASR033WUserConfigs.getInstance().getRFIDStatus()) {
                ASR033W.sharedInstance().startInventoryAntenna1(true, true, true, true, true, true, true, true, true);
            } else {
                showOpenRFIDDialog();
            }
        } else if (v.getId() == R.id.stop_title) {
            if (ASR033WUserConfigs.getInstance().getRFIDStatus()) {
                ASR033W.sharedInstance().stopInventory();
            } else {
                showOpenRFIDDialog();
            }
        } else if (v.getId() == R.id.clear_title) {
            count = 0;
            total = 0;
            countTextView.setText("Count:  " + count);
            totalTextView.setText("Total:  " + total);
            dataDic.clear();
            listAdapter.clearItems();
        } else if (v.getId() == R.id.tcp) {
            ASR033W.sharedInstance().setASR033WConnectMethod(ASR033WConnectMethod.ASR033WConnectMethod_TCP);
            tcpTextView.setBackground(tealColor);
            mqttTextView.setBackground(grayColor);
            port.setText("9600");
        } else if (v.getId() == R.id.mqtt) {
            ASR033W.sharedInstance().setASR033WConnectMethod(ASR033WConnectMethod.ASR033WConnectMethod_MQTT);
            tcpTextView.setBackground(grayColor);
            mqttTextView.setBackground(tealColor);
            port.setText("1883");
        } else if (v.getId() == R.id.rfid) {
            if (rfidSwitch.isChecked()) {
                ASR033W.sharedInstance().startReceiveRFIDData();
            } else {
                ASR033W.sharedInstance().stopReceiveRFIDData();
            }
            ASR033WUserConfigs.getInstance().setRFIDStatus(rfidSwitch.isChecked());
        } else if (v.getId() == R.id.hid) {
            if (hidSwitch.isChecked()) {
                ASR033W.sharedInstance().startReceiveHIDData();
            } else {
                ASR033W.sharedInstance().stopReceiveHIDData();
            }
            ASR033WUserConfigs.getInstance().setHIDStatus(hidSwitch.isChecked());
        }
    }
    public void connect (String host,int hostPort){
        ip.setText(host);
        port.setText(String.format("%d",hostPort));
        if (dialog != null){
            if (dialog.isShowing()){
                dialog.dismiss();
            }
        }
        dialog = new ProgressHUDBuilder(MainActivity.this).setTitle("Connecting ...");
        dialog.show();
        ASR033W.sharedInstance().connectServerWithIP(host, hostPort);
    }
    @Override
    protected void onStop() {
        super.onStop();
        ASR033W.sharedInstance().stopInventory();
    }
    private  ArrayList<String> ipItems = new ArrayList<>();
    @Override
    protected void onResume() {
        super.onResume();
        searchStatus = false;
        ip.setText(ASR033WUserConfigs.getInstance().getIP());
        Drawable tealColor = getResources().getDrawable(R.color.red);
        Drawable grayColor = getResources().getDrawable(R.color.gray);
        if (ASR033WManager.getInstance().isConnect) {
            connect.setBackground(grayColor);
            connect.setEnabled(false);
            disconnect.setBackground(tealColor);
            disconnect.setEnabled(true);
            startTextView.setBackground(tealColor);
            startTextView.setEnabled(true);
            stopTextView.setBackground(grayColor);
            stopTextView.setEnabled(false);
            clearTextView.setBackground(tealColor);
            clearTextView.setEnabled(true);
            more.setEnabled(true);
        } else {
            connect.setBackground(tealColor);
            connect.setEnabled(true);
            disconnect.setBackground(grayColor);
            disconnect.setEnabled(false);
            startTextView.setBackground(grayColor);
            startTextView.setEnabled(false);
            stopTextView.setBackground(grayColor);
            stopTextView.setEnabled(false);
            clearTextView.setBackground(grayColor);
            clearTextView.setEnabled(false);
            more.setEnabled(false);
        }
        ASR033W.sharedInstance().setCallBack(new ASR033WCallBack() {
            @Override
            public void searchingIP(ASR033W asr033W, HashMap<String, String> dictionary, boolean isFinish) {
                Log.d("ASR033WCallBack","searchingIP dictionary:" + dictionary + "\n isFinish:" + isFinish);
                if (isFinish){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (dialog != null){
                                if (dialog.isShowing()){
                                    dialog.dismiss();
                                }
                            }
                            String[] array = new String[ipItems.size()];
                            ipItems.toArray(array);
                            if (ipItems.size() == 0){
                                SearchBuilder builder =  new SearchBuilder(MainActivity.this).setInputValue("10").setHidden(true).setCancelHidden(true);
                                dialog = builder.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                }).setTitle("Search\n\nNot found Devices");
                                dialog.show();
                            } else {
                                dialog = new ListSelectBuilder(MainActivity.this)
                                        .setArray(array, new AdapterView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                String value = array[position];
                                                String[] items = value.split("\n");
                                                ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(items));
                                                if (arrayList.size() == 3) {
                                                    String ipString = arrayList.get(0);
                                                    String[] ipItems = ipString.split(":");
                                                    ArrayList<String> ipArrayList = new ArrayList<>(Arrays.asList(ipItems));
                                                    if (ipArrayList != null && ipArrayList.size() == 2) {
                                                      String ip = ipArrayList.get(1);
                                                      if (ASR033W.sharedInstance().getASR033WConnectMethod() == ASR033WConnectMethod.ASR033WConnectMethod_TCP) {
                                                          connect(ip,9600);
                                                      } else {
                                                          connect(ip,1883);
                                                      }
                                                    }
                                                }
                                            }
                                        })
                                        .setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                            }
                                        }).setTitle("033W List");
                                dialog.show();
                            }
                        }
                    });
                } else {
                    String ipString = dictionary.get(Constants.SEARCH_HOST_SERVER_IP);
                    String serialNumberString = dictionary.get(Constants.SEARCH_RFID_READER_INFORMATION);
                    String macString = dictionary.get(Constants.SEARCH_MAC);
                    String newString = "IP:" + ipString + "\n" + "Manufacture number:" + serialNumberString + "\n" + "MAC:" + macString;
                    if (!ipItems.contains(newString) && newString.equals("") == false){
                        ipItems.add(newString);
                    }
                }
            }

            @Override
            public void changeNetworkState(ASR033W asr033W, ASR033WNetworkState state, Error error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (state == ASR033WNetworkState.ASR033WNetworkStateConnected) {
                            ASR033WManager.getInstance().isConnect = true;
                            ASR033WUserConfigs.getInstance().setIP(ip.getText().toString());
                            if (dialog != null) {
                                if (dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                            connect.setBackground(grayColor);
                            connect.setEnabled(false);
                            disconnect.setBackground(tealColor);
                            disconnect.setEnabled(true);
                            startTextView.setBackground(tealColor);
                            startTextView.setEnabled(true);
                            stopTextView.setBackground(grayColor);
                            stopTextView.setEnabled(false);
                            clearTextView.setBackground(tealColor);
                            clearTextView.setEnabled(true);
                            more.setEnabled(true);
                            rfidSwitch.setEnabled(true);
                            hidSwitch.setEnabled(true);
                            tcpTextView.setEnabled(false);
                            mqttTextView.setEnabled(false);
                            if (ASR033WUserConfigs.getInstance().getRFIDStatus()) {
                                rfidSwitch.setChecked(true);
                                ASR033W.sharedInstance().startReceiveRFIDData();
                            } else {
                                rfidSwitch.setChecked(false);
                            }
                            if (ASR033WUserConfigs.getInstance().getHIDStatus()) {
                                hidSwitch.setChecked(true);
                                ASR033W.sharedInstance().startReceiveHIDData();
                            } else {
                                hidSwitch.setChecked(false);
                            }
                        } else {
                            ASR033WManager.getInstance().isConnect = false;
                            if (!searchStatus) {
                                if (dialog != null) {
                                    if (dialog.isShowing()) {
                                        dialog.dismiss();
                                    }
                                }
                            } else {
                                searchStatus = false;
                            }
                            connect.setBackground(tealColor);
                            connect.setEnabled(true);
                            disconnect.setBackground(grayColor);
                            disconnect.setEnabled(false);
                            startTextView.setBackground(grayColor);
                            startTextView.setEnabled(false);
                            stopTextView.setBackground(grayColor);
                            stopTextView.setEnabled(false);
                            clearTextView.setBackground(grayColor);
                            clearTextView.setEnabled(false);
                            more.setEnabled(false);
                            rfidSwitch.setChecked(false);
                            hidSwitch.setChecked(false);
                            rfidSwitch.setEnabled(false);
                            hidSwitch.setEnabled(false);
                            tcpTextView.setEnabled(true);
                            mqttTextView.setEnabled(true);
//                            asr033W.setASR033WConnectMethod(ASR033WConnectMethod.ASR033WConnectMethod_TCP);
                        }
                    }
                });
            }

            @Override
            public void receivedASR033WInventoryPC(String pc, String epc, String tid, int ant, int rssi, double phase, double frequency) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        total ++;
                        DataModel model = dataDic.get(epc);
                        if (model != null) {
                            model.SetDataModel(epc, pc, String.valueOf(ant), String.format("%.1f", phase), String.format("%.3f", frequency), String.valueOf(rssi), tid, model.count + 1, "RFID");
                        } else {
                            DataModel newModel = new DataModel(epc, pc, String.valueOf(ant), String.format("%.1f", phase), String.format("%.3f", frequency), String.valueOf(rssi), tid, 1, "RFID");
                            listAdapter.addItem(newModel);
                            dataDic.put(epc, newModel);
                            count ++;
                        }
                        listAdapter.notifyDataSetChanged();
                        countTextView.setText("Count:  " + count);
                        totalTextView.setText("Total:  " + total);
                    }
                });
            }

            @Override
            public void receivedASR033WHIDData(byte[] HIDData) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String EPC = new String(HIDData, Charset.forName("ASCII"));
                        total ++;
                        DataModel model = dataDic.get(EPC);
                        if (model != null) {
                            model.SetDataModel(EPC, "", "", "", "", "", "", model.count + 1, "HID");
                        } else {
                            DataModel newModel = new DataModel(EPC, "", "", "", "", "", "", 1, "HID");
                            listAdapter.addItem(newModel);
                            dataDic.put(EPC, newModel);
                            count ++;
                        }
                        listAdapter.notifyDataSetChanged();
                        countTextView.setText("Count:  " + count);
                        totalTextView.setText("Total:  " + total);
                    }
                });
            }

            @Override
            public void receivedASR033WData(byte[] data) {

            }

            @Override
            public void receivedASR033WActionChanged(ASR033WSubCommandType action) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (action == ASR033WSubCommandType.Stop) {
                            stopTextView.setBackground(grayColor);
                            stopTextView.setEnabled(false);
                            startTextView.setBackground(tealColor);
                            startTextView.setEnabled(true);
                        } else if (action == ASR033WSubCommandType.Inventory) {
                            stopTextView.setBackground(tealColor);
                            stopTextView.setEnabled(true);
                            startTextView.setBackground(grayColor);
                            startTextView.setEnabled(true);
                        }
                    }
                });
            }

            @Override
            public void receivedASR033WRegionName(String version) {

            }

            @Override
            public void receivedASR033WSerialNumber(String version) {

            }

            @Override
            public void receivedASR033WHardwareVersion(String version) {

            }

            @Override
            public void receivedASR033WRFModuleVersion(String version) {

            }

            @Override
            public void receivedASR033WFirmwareVersion(String version) {

            }

            @Override
            public void receivedASR033WMacAddress(String value) {

            }
        });
    }
    private void showOpenRFIDDialog() {
        warningDialog = new AlertDialog.Builder(MainActivity.this);
        warningDialog.setMessage("Please open RFID!");
        warningDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        warningDialog.setCancelable(false);
        warningDialog.create();
        warningDialog.show();
    }
}