package cz.navtom.elektromer;

import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

import com.felhr.usbserial.CDCSerialDevice;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

public class UsbService extends Service {

    public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
    public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
    public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
    public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
    public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
    public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
    public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
    public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
    public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";

    private boolean BUSY                         = false;

    public static final int ACTION_SERIAL       =   1;

    public static final int ACTION_SENS_CON     =   1;
    public static final int ACTION_SENS_DISCO   =   2;
    public static final int ACTION_GET_APLUS    =   3;

    public static final int MESSAGE_FROM_SERIAL_PORT = 0;
    public static final int CTS_CHANGE = 1;
    public static final int DSR_CHANGE = 2;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    //private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
    public static boolean SERVICE_CONNECTED = false;

    private IBinder binder = new UsbBinder();

    private Context context;
    private Handler mHandler;
    private UsbManager usbManager;
    private UsbDevice device;
    private UsbDeviceConnection connection;
    private UsbSerialDevice serialPort;

    private boolean serialPortConnected;
    /*
     *  Data received from serial port will be received here. Just populate onReceivedData with your code
     *  In this particular example. byte stream is converted to String and send to UI thread to
     *  be treated there.
     */
    private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
        @Override
        public void onReceivedData(byte[] arg0) {

            if (mHandler != null)
                mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, arg0).sendToTarget();
        }
    };
    /*
     * Different notifications from OS will be received here (USB attached, detached, permission responses...)
     * About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
     */
    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
                boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
                if (granted) // User accepted our USB connection. Try to open the device as a serial port
                {
                    Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
                    arg0.sendBroadcast(intent);
                    connection = usbManager.openDevice(device);
                    serialPortConnected = true;
                    new ConnectionThread().run();
                } else // User not accepted our USB connection. Send an Intent to the Main Activity
                {
                    Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
                    arg0.sendBroadcast(intent);
                }
            } else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
                if (!serialPortConnected)
                    findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
            } else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
                // Usb device was disconnected. send an intent to the Main Activity
                Intent intent = new Intent(ACTION_USB_DISCONNECTED);
                arg0.sendBroadcast(intent);
                serialPortConnected = false;
                serialPort.close();
                Toast.makeText(getApplicationContext(),"PortClosed",Toast.LENGTH_SHORT).show();
            }
        }
    };

    /*
     * onCreate will be executed when service is started. It configures an IntentFilter to listen for
     * incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
     */
    @Override
    public void onCreate() {
        this.context = this;
        serialPortConnected = false;
        UsbService.SERVICE_CONNECTED = true;
        setFilter();
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        findSerialPortDevice();
    }

    /* MUST READ about services
     * http://developer.android.com/guide/components/services.html
     * http://developer.android.com/guide/components/bound-services.html
     */
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UsbService.SERVICE_CONNECTED = false;
    }

    /*
     * This function will be called from MainActivity to write data through Serial Port
     */
    public void write(byte[] data) {
        if (serialPort != null)
            serialPort.write(data);
    }

    public void setHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }

    private void findSerialPortDevice() {
        // This snippet will try to open the first encountered usb device connected, excluding usb root hubs
        HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
        if (!usbDevices.isEmpty()) {
            boolean keep = true;
            for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
                device = entry.getValue();
                int deviceVID = device.getVendorId();
                int devicePID = device.getProductId();

                if (deviceVID != 0x1d6b && (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
                    // There is a device connected to our Android device. Try to open it as a Serial Port.
                    requestUserPermission();
                    keep = false;
                } else {
                    connection = null;
                    device = null;
                }

                if (!keep)
                    break;
            }
            if (!keep) {
                // There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
                Intent intent = new Intent(ACTION_NO_USB);
                sendBroadcast(intent);
            }
        } else {
            // There is no USB devices connected. Send an intent to MainActivity
            Intent intent = new Intent(ACTION_NO_USB);
            sendBroadcast(intent);
        }
    }

    private void setFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(ACTION_USB_DETACHED);
        filter.addAction(ACTION_USB_ATTACHED);
        registerReceiver(usbReceiver, filter);
    }

    /*
     * Request user permission. The response will be received in the BroadcastReceiver
     */
    private void requestUserPermission() {
        PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        usbManager.requestPermission(device, mPendingIntent);
    }

    public class UsbBinder extends Binder {
        public UsbService getService() {
            return UsbService.this;
        }
    }

    /*
     * A simple thread to open a serial port.
     * Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
     */
    private class ConnectionThread extends Thread {
        @Override
        public void run() {
            serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
            if (serialPort != null) {
                if (serialPort.open()) {
                    /*serialPort.setBaudRate(300);
                    serialPort.setDataBits(UsbSerialInterface.DATA_BITS_7);
                    serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
                    serialPort.setParity(UsbSerialInterface.PARITY_EVEN);
                    serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);*/
                    serialPort.read(mCallback);

                    // Everything went as expected. Send an intent to MainActivity
                    Intent intent = new Intent(ACTION_USB_READY);
                    context.sendBroadcast(intent);
                } else {
                    // Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
                    // Send an Intent to Main Activity
                    if (serialPort instanceof CDCSerialDevice) {
                        Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
                        context.sendBroadcast(intent);
                    } else {
                        Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
                        context.sendBroadcast(intent);
                    }
                }
            } else {
                // No driver for given device, even generic CDC driver could not be loaded
                Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
                context.sendBroadcast(intent);
            }
        }
    }


    public void Obsluha(int action, int param) {

        switch (action) {
            //operace se seriovou linkou
            case ACTION_SERIAL:
                new ElektromerConnection(param).execute();
                break;

            default:
                break;
        }
    }

    public boolean isBusy() {

        return BUSY;

    }

    /* Pripojeni k elektromeru dle DLMS/COSEM */
    private class ElektromerConnection extends AsyncTask {

        private int action;

        public ElektromerConnection(int param) {

            action = param;
        }

        private void sendData(byte[] data, int waitTime) {
            if (serialPort == null) return;

            serialPort.write(data);

            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            serialPort.read(mCallback);
        }

        byte[] hello1 = new byte[]{(byte) 0x2F, (byte) 0x3F, (byte) 0x21, (byte) 0x0D, (byte) 0x0A};
        byte[] hello2 = new byte[]{(byte) 0x06, (byte) 0x32, (byte) 0x35, (byte) 0x32, (byte) 0x0D, (byte) 0x0A};
        byte[] hello3 = new byte[]{(byte) 0x7E, (byte) 0xA0, (byte) 0x21, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x93, (byte) 0x48, (byte) 0xF3, (byte) 0x81, (byte) 0x80, (byte) 0x14, (byte) 0x05, (byte) 0x02, (byte) 0x07, (byte) 0xEE, (byte) 0x06, (byte) 0x02, (byte) 0x07, (byte) 0xEE, (byte) 0x07, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x08, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0xB5, (byte) 0xD4, (byte) 0x7E};
        byte[] hello4 = new byte[]{(byte) 0x7e, (byte) 0xa0, (byte) 0x59, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x10, (byte) 0x08, (byte) 0x0a, (byte) 0xe6, (byte) 0xe6, (byte) 0x00, (byte) 0x60, (byte) 0x4a, (byte) 0xa1, (byte) 0x09, (byte) 0x06, (byte) 0x07, (byte) 0x60, (byte) 0x85, (byte) 0x74, (byte) 0x05, (byte) 0x08, (byte) 0x01, (byte) 0x01, (byte) 0xa6, (byte) 0x0a, (byte) 0x04, (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x8a, (byte) 0x02, (byte) 0x07, (byte) 0x80, (byte) 0x8b, (byte) 0x07, (byte) 0x60, (byte) 0x85, (byte) 0x74, (byte) 0x05, (byte) 0x08, (byte) 0x02, (byte) 0x05, (byte) 0xac, (byte) 0x12, (byte) 0x80, (byte) 0x10, (byte) 0x55, (byte) 0x9d, (byte) 0x5d, (byte) 0x59, (byte) 0xdb, (byte) 0xa7, (byte) 0xbd, (byte) 0x40, (byte) 0x07, (byte) 0xb8, (byte) 0x2c, (byte) 0xa1, (byte) 0x29, (byte) 0x07, (byte) 0x2e, (byte) 0x0e, (byte) 0xbe, (byte) 0x10, (byte) 0x04, (byte) 0x0e, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x5f, (byte) 0x1f, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x1f, (byte) 0x1f, (byte) 0xff, (byte) 0xfd, (byte) 0x48, (byte) 0x95, (byte) 0x7e};
        byte[] hello5 = new byte[]{(byte) 0x7e, (byte) 0xa0, (byte) 0x2d, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x32, (byte) 0xfb, (byte) 0x30, (byte) 0xe6, (byte) 0xe6, (byte) 0x00, (byte) 0xc3, (byte) 0x01, (byte) 0xc1, (byte) 0x00, (byte) 0x0f, (byte) 0x00, (byte) 0x00, (byte) 0x28, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0x01, (byte) 0x01, (byte) 0x09, (byte) 0x11, (byte) 0x10, (byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67, (byte) 0xfb, (byte) 0xee, (byte) 0x0d, (byte) 0x82, (byte) 0xe8, (byte) 0xe2, (byte) 0x62, (byte) 0x72, (byte) 0xf6, (byte) 0xf7, (byte) 0xec, (byte) 0x78, (byte) 0xaa, (byte) 0x4b, (byte) 0x7e};
        byte[] bye1 = new byte[]{(byte) 0x7e, (byte) 0xa0, (byte) 0x08, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x53, (byte) 0xb1, (byte) 0x04, (byte) 0x7e};
        byte[] req1 = new byte[]{(byte) 0x7e, (byte) 0xa0, (byte) 0x1a, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x54, (byte) 0xc6, (byte) 0xd2, (byte) 0xe6, (byte) 0xe6, (byte) 0x00, (byte) 0xc0, (byte) 0x01, (byte) 0xc1, (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x08, (byte) 0x00, (byte) 0xff, (byte) 0x02, (byte) 0x00, (byte) 0x32, (byte) 0x68, (byte) 0x7e };
        byte[] req2 = new byte[]{(byte) 0x7e, (byte) 0xa0, (byte) 0x1a, (byte) 0x02, (byte) 0x01, (byte) 0x03, (byte) 0x76, (byte) 0xd6, (byte) 0xd0, (byte) 0xe6, (byte) 0xe6, (byte) 0x00, (byte) 0xc0, (byte) 0x01, (byte) 0xc1, (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x08, (byte) 0x00, (byte) 0xff, (byte) 0x03, (byte) 0x00, (byte) 0xea, (byte) 0x71, (byte) 0x7e};


        @Override
        protected Object doInBackground(Object[] params) {

            if (serialPort == null) return null;

            BUSY = true;

            switch (action) {
                //pripojeni k elmeru
                case ACTION_SENS_CON:

                    serialPort.setBaudRate(300);
                    serialPort.setDataBits(UsbSerialInterface.DATA_BITS_7);
                    serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
                    serialPort.setParity(UsbSerialInterface.PARITY_EVEN);
                    serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);


                    sendData(hello1, 1300);
                    sendData(hello2, 500);


                    serialPort.setBaudRate(9600);
                    serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
                    serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
                    serialPort.setParity(UsbSerialInterface.PARITY_NONE);


                    sendData(hello3, 500);
                    sendData(hello4, 700);
                    sendData(hello5, 500);


                    break;

                //odpojeni od elmeru
                case ACTION_SENS_DISCO:

                    sendData(bye1, 1000);
                    //serialPort.close();


                    break;

                //odecet hodnoty A+
                case ACTION_GET_APLUS:

                    sendData(req1, 400);
                    sendData(req2, 400);

                    break;

                default:
                    break;
            }

            BUSY = false;

            return null;
        }
    }
}
