package com.ssiltda.printerapp;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import static android.os.Environment.getExternalStorageDirectory;

public class Inicio extends AppCompatActivity {
    private int READ_EXTERNAL_STORAGE_PERMISSIONS;
    TextView lblNumFact, lblClieFact, lblTitulo, lblTotal, lblEstado;
    Button btnImprimir;
    String impresora, nitCompania, nombreCompania, direccionCompania, telefonoCompania;
    DecimalFormat decimal = new DecimalFormat("###,###.#");
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    volatile boolean stopWorker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inicio);
        lblEstado = (TextView) findViewById(R.id.txtEstado);
        lblNumFact = (TextView) findViewById(R.id.fact);
        lblClieFact = (TextView) findViewById(R.id.client);
        lblTitulo = (TextView) findViewById(R.id.titulo);
        lblTotal = (TextView) findViewById(R.id.total);
        btnImprimir = (Button) findViewById(R.id.send);
        Button sendButton = (Button) findViewById(R.id.send);
        Button closeButton = (Button) findViewById(R.id.close);
        Button CambVend = (Button) findViewById(R.id.cmbvend);
        CambVend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentConfv();
            }
        });
        sendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                imprimir();
            }
        });
        closeButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                cerrar();
            }
        });
        confVend();
        if(nitCompania.equals("") || nombreCompania.equals("")){
            intentConfv();
        }else{
            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }else{
                ValidarXML();
            }
        }
    }

    @Override
    public void onResume (){
        super.onResume();
        confVend();
        if(nitCompania.equals("") || nombreCompania.equals("")){
            intentConfv();
        }else{
            ValidarXML();
        }
    }

    private void ValidarXML(){
        String path = getExternalStorageDirectory()+"/imprfact.xml";
        File file = new File(path);
        if(file.exists()){
            btnImprimir.setEnabled(true);
            EncabezadoFactura();
        }else{
            btnImprimir.setEnabled(false);
            lblTitulo.setText("Resumen Factura");
            lblNumFact.setText("No hay facturas para imprimir");
            lblClieFact.setText("Cliente: ");
            lblTotal.setText("Total Factura: $ 0");
        }
    }

    private void imprimir(){
        findBT();
    }

    private void cerrar(){
        try {
            closeBT();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    ValidarXML();
                } else {
                    Toast.makeText(this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    public void EncabezadoFactura(){
        XmlPullParserFactory pullParserFactory;
        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();
            String path = getExternalStorageDirectory()+"/imprfact.xml";
            File file = new File(path);
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream in_s = fileInputStream;
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);
            ArrayList<itemImpr> items =  parseXML(parser);
            lblTitulo.setText("Resumen Factura");
            lblNumFact.setText("Factura de venta N°: "+items.get(0).getFactprefijo().toString()+"  "+items.get(0).getFactnumumero().toString());
            lblClieFact.setText("Cliente: "+items.get(0).getNomcliente().toString());
            lblTotal.setText("Total Factura: $ "+decimal.format(Double.parseDouble(items.get(0).getTotaldoc())));
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ArrayList<itemImpr> parseXML(XmlPullParser parser) throws XmlPullParserException,IOException {
        ArrayList<itemImpr> items = null;
        int eventType = parser.getEventType();
        itemImpr item = null;
        while (eventType != XmlPullParser.END_DOCUMENT){
            String name;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    items = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equals("item")){
                        item = new itemImpr();
                    } else if (item != null){
                        if (name.equals("factprefijo")){
                            item.setFactprefijo(parser.nextText());
                        }else if (name.equals("factnumumero")){
                            item.setFactnumumero(parser.nextText());
                        }else if (name.equals("factfecha")){
                            item.setFactfecha(parser.nextText());
                        }else if (name.equals("autonum")){
                            item.setAutonum(parser.nextText());
                        }else if (name.equals("autodesde")){
                            item.setAutodesde(parser.nextText());
                        }else if (name.equals("autohasta")){
                            item.setAutohasta(parser.nextText());
                        }else if (name.equals("autofecha")){
                            item.setAutofecha(parser.nextText());
                        }else if (name.equals("articant")){
                            item.setArticant(parser.nextText());
                        }else if (name.equals("artidesc")){
                            item.setArtidesc(parser.nextText());
                        }else if (name.equals("artiund")){
                            item.setArtiund(parser.nextText());
                        }else if (name.equals("artiprunit")){
                            item.setArtiprunit(parser.nextText());
                        }else if (name.equals("artiprtotal")){
                            item.setArtiprtotal(parser.nextText());
                        }else if (name.equals("totaldoc")){
                            item.setTotaldoc(parser.nextText());
                        }else if (name.equals("totitems")){
                            item.setTotitems(parser.nextText());
                        }else if (name.equals("baseiva0")){
                            item.setBaseiva0(parser.nextText());
                        }else if (name.equals("montoiva0")){
                            item.setMontoiva0(parser.nextText());
                        }else if (name.equals("baseiva19")){
                            item.setBaseiva19(parser.nextText());
                        }else if (name.equals("montoiva19")){
                            item.setMontoiva19(parser.nextText());
                        }else if (name.equals("nitcliente")){
                            item.setNitcliente(parser.nextText());
                        }else if (name.equals("nomcliente")){
                            item.setNomcliente(parser.nextText());
                        }else if (name.equals("nomvend")){
                            item.setNomvend(parser.nextText());
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("item") && item != null){
                        items.add(item);
                    }
            }
            eventType = parser.next();
        }
        return items;
    }

    private void confVend() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        impresora = preferences.getString("nombImpresora", "").toString();
        nitCompania = preferences.getString("nitComp", "").toString();
        nombreCompania = preferences.getString("nombComp", "").toString();
        direccionCompania = preferences.getString("dirComp", "").toString();
        telefonoCompania = preferences.getString("telComp", "").toString();
        if (impresora.equals("")){
            SharedPreferences.Editor editorS = preferences.edit();
            editorS.putString("nombImpresora", "BlueTooth Printer");
            editorS.apply();
        }
    }

    public void intentConfv(){
        startActivity(new Intent(getBaseContext(), configVend.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP));
        finish();
    }

    void emparejarImpresora(){
        try {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if(pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    lblEstado.setTextColor(getResources().getColorStateList(R.color.verde));
                    lblEstado.setText("Bluetooth dispositivo encontrado." + device.getName());
                    if (device.getName().equals(impresora)) {
                        mmDevice = device;
                        lblEstado.setTextColor(getResources().getColorStateList(R.color.verde));
                        lblEstado.setText("Bluetooth dispositivo "+device.getName()+" encontrado.");
                        openBT();
                        break;
                    }
                }
            }else{
                lblEstado.setTextColor(getResources().getColorStateList(R.color.rojo));
                lblEstado.setText("No se encontraron dispositivos vinculados");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }
    // this will find a bluetooth printer device
    void findBT() {
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if(mBluetoothAdapter == null) {
                lblEstado.setTextColor(getResources().getColorStateList(R.color.rojo));
                lblEstado.setText("Adaptador Bluetooth no disponible");
            }
            if(!mBluetoothAdapter.isEnabled()) {
                Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
                startActivity(discoverableIntent);
                lblEstado.setTextColor(getResources().getColorStateList(R.color.rojo));
                lblEstado.setText("Si activo el bluetooth intente imprimir nuevamente, de lo contrario active el Bluetooth para continuar.");
            }else{
                emparejarImpresora();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    // tries to open a connection to the bluetooth printer device
    void openBT() throws IOException {
        try {
            // Standard SerialPortService ID
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            if (!mmSocket.isConnected()){
                mmSocket.connect();
            }
            mmOutputStream = mmSocket.getOutputStream();
            mmInputStream = mmSocket.getInputStream();
            beginListenForData();
            lblEstado.setTextColor(getResources().getColorStateList(R.color.verde));
            lblEstado.setText("Bluetooth Abierto");
            sendData();
        } catch (Exception e) {
            if (!mmSocket.isConnected()){
                lblEstado.setTextColor(getResources().getColorStateList(R.color.rojo));
                lblEstado.setText("No se pudo establecer la conexion con la impresora "+mmDevice.getName());
            }
            e.printStackTrace();
        }
    }

    /* after opening a connection to bluetooth printer device, we have to listen and check if a data were sent to be printed.*/
    void beginListenForData() {
        try {
            final Handler handler = new Handler();
            // this is the ASCII code for a newline character
            final byte delimiter = 10;
            stopWorker = false;
            readBufferPosition = 0;
            readBuffer = new byte[1024];
            workerThread = new Thread(new Runnable() {
                public void run() {
                    while (!Thread.currentThread().isInterrupted() && !stopWorker) {
                        try {
                            int bytesAvailable = mmInputStream.available();
                            if (bytesAvailable > 0) {
                                byte[] packetBytes = new byte[bytesAvailable];
                                mmInputStream.read(packetBytes);
                                for (int i = 0; i < bytesAvailable; i++) {
                                    byte b = packetBytes[i];
                                    if (b == delimiter) {
                                        byte[] encodedBytes = new byte[readBufferPosition];
                                        System.arraycopy(
                                                readBuffer, 0,
                                                encodedBytes, 0,
                                                encodedBytes.length
                                        );
                                        // specify US-ASCII encoding
                                        final String data = new String(encodedBytes, "US-ASCII");
                                        readBufferPosition = 0;
                                        // tell the user data were sent to bluetooth printer device
                                        handler.post(new Runnable() {
                                            public void run() {
                                                lblEstado.setText(data);
                                            }
                                        });
                                    } else {
                                        readBuffer[readBufferPosition++] = b;
                                    }
                                }
                            }
                        } catch (IOException ex) {
                            stopWorker = true;
                        }
                    }
                }
            });
            workerThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // this will send text data to be printed by the bluetooth printer
    void sendData() throws IOException {
        try {
            XmlPullParserFactory pullParserFactory;
            try {
                pullParserFactory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = pullParserFactory.newPullParser();
                String path = getExternalStorageDirectory()+"/imprfact.xml";
                File file = new File(path);
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStream in_s = fileInputStream;
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                parser.setInput(in_s, null);
                ArrayList<itemImpr> items=  parseXML(parser);
                Stream st = new Stream();
                String msg = "";
                //enviar encabezado
                msg += "    "+nombreCompania+System.getProperty("line.separator");
                msg += "          "+nitCompania+System.getProperty("line.separator");
                msg += "Res. DIAN No "+items.get(0).getAutonum().toString()+System.getProperty("line.separator");
                msg += "Desde: "+items.get(0).getAutodesde().toString()+" Hasta: "+items.get(0).getAutohasta().toString()+System.getProperty("line.separator");
                msg += "Factura de Venta: "+items.get(0).getFactprefijo().toString()+" "+items.get(0).getFactnumumero().toString()+System.getProperty("line.separator");
                msg += "Fecha/Hora: "+items.get(0).getFactfecha().toString()+System.getProperty("line.separator");
                msg += "--------------------------------"+System.getProperty("line.separator");
                msg += " CANT      DESCRIPCION"+System.getProperty("line.separator");
                msg += "UNIDAD       PRECIO      TOTAL"+System.getProperty("line.separator");
                msg += "--------------------------------"+System.getProperty("line.separator");
                mmOutputStream.write(msg.getBytes());
                msg = "";
                //imprimir detalle
                for(itemImpr item:items) {
                    msg += st.tamDato(decimal.format(Double.parseDouble(item.getArticant())),4,"D")+"  "+st.tamDato(item.getArtidesc(),20,"N")+System.getProperty("line.separator");
                    msg += st.tamDato(item.getArtiund(),6,"D")+"     $"+st.tamDato(decimal.format(Double.parseDouble(item.getArtiprunit())),6,"D")+"  $"+st.tamDato(decimal.format(Double.parseDouble(item.getArtiprtotal())),6,"N")+System.getProperty("line.separator");
                    mmOutputStream.write(msg.getBytes());
                    msg = "";
                }
                //imprimir liquidacion
                msg += System.getProperty("line.separator")+msg+"          TOTAL:      $"+st.tamDato(decimal.format(Double.parseDouble(items.get(0).getTotaldoc())),10,"N")+System.getProperty("line.separator");
                msg += "--------------------------------"+System.getProperty("line.separator");
                msg += "Total articulos vendidos:   "+items.get(0).getTotitems()+System.getProperty("line.separator");
                msg += "      **Detalle del IVA**"+System.getProperty("line.separator");
                msg += "Tipo    Base / Imp     IVA"+System.getProperty("line.separator");
                msg += "19%      $"+st.tamDato(decimal.format(Double.parseDouble(items.get(0).getBaseiva19())),10,"D")+"  $"+st.tamDato(decimal.format(Double.parseDouble(items.get(0).getMontoiva19())),10,"N")+System.getProperty("line.separator");
                msg += " 0%      $"+st.tamDato(decimal.format(Double.parseDouble(items.get(0).getBaseiva0())),10,"D")+"  $"+st.tamDato(decimal.format(Double.parseDouble(items.get(0).getMontoiva0())),10,"N")+System.getProperty("line.separator");
                msg += "--------------------------------"+System.getProperty("line.separator");
                msg += "Cliente: "+st.tamDato(items.get(0).getNomcliente(),25,"N")+System.getProperty("line.separator");
                msg += "Nit / CC: "+items.get(0).getNitcliente()+System.getProperty("line.separator");
                msg += "Vendedor: "+st.tamDato(items.get(0).getNomvend(),25,"D")+System.getProperty("line.separator");
                mmOutputStream.write(msg.getBytes());
                lblEstado.setTextColor(getResources().getColorStateList(R.color.verde));
                lblEstado.setText("Datos Enviados.");
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            lblEstado.setTextColor(getResources().getColorStateList(R.color.rojo));
            lblEstado.setText("No se pudo enviar la impresion.");
            e.printStackTrace();
        }
        closeBT();
    }

    // close the connection to bluetooth printer.
    void closeBT() throws IOException {
        try {
            stopWorker = true;
            if (mmOutputStream != null){
                mmOutputStream.close();
            }
            if (mmInputStream != null){
                mmInputStream.close();
            }
            if (mmSocket != null){
                mmSocket.close();
            }
        } catch (Exception e) {
            lblEstado.setTextColor(getResources().getColor(R.color.rojo ));
            lblEstado.setText("Se presento el siguiente error: "+e.getMessage());
            e.printStackTrace();
        }
        System.exit(0);
    }

}