package com.bixolon.sample;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bixolon.BixolonConst;
import com.bixolon.commonlib.common.BXLHelper;
import com.bixolon.mpos.MPosControllerConfig;
import com.bixolon.mpos.config.util.MPosControllerLookup;

public class ConfigFragment extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    private RadioGroup radioGroupPortType;

    private EditText editTextAddress = null;

    private int portType = BixolonConst.MPOS_INTERFACE_BLUETOOTH;

    public static ConfigFragment newInstance() {
        ConfigFragment fragment = new ConfigFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_config, container, false);

        editTextAddress = view.findViewById(R.id.editTextAddress);
        editTextAddress.setText("74:F0:7D:10:10:01");

        radioGroupPortType = view.findViewById(R.id.radioGroupPortType);
        radioGroupPortType.setOnCheckedChangeListener(this);

        view.findViewById(R.id.btnGetAddress).setOnClickListener(this);
        view.findViewById(R.id.btnOpen).setOnClickListener(this);
        view.findViewById(R.id.btnClose).setOnClickListener(this);
        view.findViewById(R.id.btnGetInfo).setOnClickListener(this);
        view.findViewById(R.id.btnPrintInfo).setOnClickListener(this);
        view.findViewById(R.id.btnGetBluetoothInfo).setOnClickListener(this);
        view.findViewById(R.id.btnGetSerialInfo).setOnClickListener(this);
        view.findViewById(R.id.btnGetWlanInfo).setOnClickListener(this);
        view.findViewById(R.id.btnGetEthernetInfo).setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnGetAddress:
                try {
                    String[] items = null;
                    if (BixolonConst.MPOS_SUCCESS == MPosControllerLookup.refreshDeviceList(portType, 3)) {
                        MPosControllerLookup.MPosDeviceInfo[] deviceInfos = MPosControllerLookup.getDeviceList(portType);
                        if (deviceInfos != null && deviceInfos.length > 0) {
                            items = new String[deviceInfos.length];
                            if (portType == BixolonConst.MPOS_INTERFACE_BLUETOOTH) {
                                for (int i = 0; i < deviceInfos.length; i++) {
                                    items[i] = deviceInfos[i].deviceName + "\n" + deviceInfos[i].macAddress;
                                }
                            } else if (portType == BixolonConst.MPOS_INTERFACE_WIFI) {
                                for (int i = 0; i < deviceInfos.length; i++) {
                                    items[i] = deviceInfos[i].ipAddress;
                                }
                            }

                            final String[] finalItems = items;
                            new AlertDialog.Builder(getContext()).setTitle("Device List")
                                    .setItems(items, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            String strSelectList = finalItems[which];
                                            String strDeviceInfo = null;
                                            if (portType == BixolonConst.MPOS_INTERFACE_BLUETOOTH) {
                                                String[] splitAddr = strSelectList.split("\n");
                                                strDeviceInfo = splitAddr[1];
                                            } else {
                                                strDeviceInfo = strSelectList;
                                            }
                                            editTextAddress.setText(strDeviceInfo);
                                        }
                                    }).show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btnOpen:
                openService();
                break;
            case R.id.btnClose:
                closeService();
                break;
            case R.id.btnGetInfo:
                getPrinterSettingInfo();
                break;
            case R.id.btnPrintInfo:
                printSettingInfo();
                break;
            case R.id.btnGetBluetoothInfo:
                getBluetoothInfo();
                break;
            case R.id.btnGetSerialInfo:
                getSerialInfo();
                break;
            case R.id.btnGetWlanInfo:
                getWlanInfo();
                break;
            case R.id.btnGetEthernetInfo:
                getEthernetInfo();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.radioBT:
                editTextAddress.setText("74:F0:7D:00:00:00");
                portType = BixolonConst.MPOS_INTERFACE_BLUETOOTH;
                break;
            case R.id.radioWifi:
                editTextAddress.setText("192.168.0.1");
                portType = BixolonConst.MPOS_INTERFACE_WIFI;
                break;
            case R.id.radioUSB:
                editTextAddress.setText("");
                portType = BixolonConst.MPOS_INTERFACE_USB;
                break;
        }
    }

    private void openService() {
        String strAddress = editTextAddress.getText().toString();

        MainActivity.mPosControllerConfig.selectCommandMode(BixolonConst.MPOS_COMMAND_MODE_DEFAULT);
        MainActivity.mPosControllerConfig.selectInterface(portType, strAddress);
        long ret = MainActivity.mPosControllerConfig.openService(getContext());
        if(ret != BixolonConst.MPOS_SUCCESS) {
            Toast.makeText(getContext(), "Device open fail : " + ret, Toast.LENGTH_LONG).show();
            return;
        }
    }

    private void closeService() {
        if(MainActivity.mPosControllerConfig.isOpen()) {
            MainActivity.mPosControllerConfig.closeService(0);
        }
    }

    private void getPrinterSettingInfo() {
        if(!MainActivity.mPosControllerConfig.isOpen()) {
            Toast.makeText(getContext(), "Device not opened.", Toast.LENGTH_LONG).show();
            return;
        }

        String showMsg = "";
        String strInfo;
        byte[] arInfo;
        byte byInfo;

        strInfo = MainActivity.mPosControllerConfig.getModelName(BixolonConst.MPOS_DEVICE_CONFIG);
        if(strInfo != null && !strInfo.isEmpty()) showMsg += ("ModelName : " + strInfo + "\n");

        strInfo = MainActivity.mPosControllerConfig.getFirmwareVersion(BixolonConst.MPOS_DEVICE_CONFIG);
        if(strInfo != null && !strInfo.isEmpty()) showMsg += ("FirmwareVersion : " + strInfo + "\n");

        strInfo = MainActivity.mPosControllerConfig.getWebToolsVersion(BixolonConst.MPOS_DEVICE_CONFIG);
        if(strInfo != null && !strInfo.isEmpty()) showMsg += ("WebToolsVersion : " + strInfo + "\n");

        strInfo = MainActivity.mPosControllerConfig.getWebAppVersion(BixolonConst.MPOS_DEVICE_CONFIG);
        if(strInfo != null && !strInfo.isEmpty()) showMsg += ("WebAppVersion : " + strInfo + "\n");

        byInfo = MainActivity.mPosControllerConfig.getUsbPrinterStatus(BixolonConst.MPOS_DEVICE_CONFIG);
        if(byInfo != -1) showMsg += ("UsbPrinterStatus : " + byInfo + "\n");

        arInfo = MainActivity.mPosControllerConfig.getBGateSerialNumber();
        if(arInfo != null && arInfo.length > 0) showMsg += ("BGateSerialNumber : " + new String(arInfo) + "\n");

        if(showMsg.length() > 0) {
            Toast.makeText(getContext(), showMsg, Toast.LENGTH_LONG).show();
        }
    }

    private void printSettingInfo() {
        if(!MainActivity.mPosControllerConfig.isOpen()) {
            Toast.makeText(getContext(), "Device not opened.", Toast.LENGTH_LONG).show();
            return;
        }

        MainActivity.mPosControllerConfig.printSelfTestPage();
        MainActivity.mPosControllerConfig.printBTSetting();
        MainActivity.mPosControllerConfig.printLanSetting();
        MainActivity.mPosControllerConfig.printWlanSetting();
    }

    private void getBluetoothInfo() {
        if(!MainActivity.mPosControllerConfig.isOpen()) {
            Toast.makeText(getContext(), "Device not opened.", Toast.LENGTH_LONG).show();
            return;
        }

        String showMsg = "";
        String strInfo;
        byte[] arInfo;
        int nInfo;

        nInfo = MainActivity.mPosControllerConfig.getBluetoothConnectionMode(BixolonConst.MPOS_DEVICE_CONFIG);
        if(nInfo != -1) showMsg += ("BluetoothConnectionMode : " + nInfo + "\n");

        strInfo = MainActivity.mPosControllerConfig.getBluetoothName(BixolonConst.MPOS_DEVICE_CONFIG);
        if(strInfo != null && !strInfo.isEmpty()) showMsg += ("BluetoothName : " + strInfo + "\n");

        strInfo = MainActivity.mPosControllerConfig.getBluetoothPinCode(BixolonConst.MPOS_DEVICE_CONFIG);
        if(strInfo != null && !strInfo.isEmpty()) showMsg += ("BluetoothPinCode : " + strInfo + "\n");

        nInfo = MainActivity.mPosControllerConfig.getBluetoothAuthentication(BixolonConst.MPOS_DEVICE_CONFIG);
        if(nInfo != -1) showMsg += ("BluetoothAuthentication : " + nInfo + "\n");

        arInfo = MainActivity.mPosControllerConfig.getBluetoothMacAddress();
        if(arInfo != null && arInfo.length > 0) showMsg += ("BluetoothMacAddress : " + BXLHelper.Hex2HexStr(arInfo, arInfo.length, true, true) + "\n");

        nInfo = MainActivity.mPosControllerConfig.getBluetoothAutoConnection();
        if(nInfo != -1) showMsg += ("BluetoothAutoConnection : " + nInfo + "\n");

        if(showMsg.length() > 0) {
            Toast.makeText(getContext(), showMsg, Toast.LENGTH_LONG).show();
        }
    }

    private void getSerialInfo() {
        if(!MainActivity.mPosControllerConfig.isOpen()) {
            Toast.makeText(getContext(), "Device not opened.", Toast.LENGTH_LONG).show();
            return;
        }

        byte[] serial = MainActivity.mPosControllerConfig.getSerialConfiguration(BixolonConst.MPOS_DEVICE_CONFIG);
        if(serial != null && serial.length > 0) {
            // baud rate (0: 2400 / 1: 4800 / 2: 9600 / 3: 19200 / 4: 38400 / 5: 57600 / 6: 115,200 / 7: 230,400)
            // data bit (0: 7bits / 1: 8bits)
            // stop bit (0: 1bit / 1: 2bits)
            // parity bit (0: None / 1: Even / 2: Odd)
            // flow control (0: H/W / 1: None)
            String showMsg = "";
            showMsg += ("baud rate : " + serial[0] + "\n");
            showMsg += ("data bit : " + serial[1] + "\n");
            showMsg += ("stop bit : " + serial[2] + "\n");
            showMsg += ("parity bit : " + serial[3] + "\n");
            showMsg += ("flow control : " + serial[4] + "\n");
            Toast.makeText(getContext(), showMsg, Toast.LENGTH_LONG).show();
        }
    }

    private void getWlanInfo() {
        if(!MainActivity.mPosControllerConfig.isOpen()) {
            Toast.makeText(getContext(), "Device not opened.", Toast.LENGTH_LONG).show();
            return;
        }

        MPosControllerConfig.WLANConfigInfo wlanConfigInfo = MainActivity.mPosControllerConfig.getWlanInfo();
        if(wlanConfigInfo != null) {
            Toast.makeText(getContext(), wlanConfigInfo.toString(), Toast.LENGTH_LONG).show();
        }
    }

    private void getEthernetInfo() {
        if(!MainActivity.mPosControllerConfig.isOpen()) {
            Toast.makeText(getContext(), "Device not opened.", Toast.LENGTH_LONG).show();
            return;
        }

        MPosControllerConfig.LANConfigInfo lanConfigInfo = MainActivity.mPosControllerConfig.getLanInfo();
        if(lanConfigInfo != null) {
            Toast.makeText(getContext(), lanConfigInfo.toString(), Toast.LENGTH_LONG).show();
        }
    }
}
