package org.apache.cordova.calender;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.andprn.jpos.command.ESCPOS;
import com.andprn.jpos.printer.ESCPOSPrinter;
import com.andprn.port.android.WiFiPort;
import com.andprn.request.android.RequestHandler;



import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;

/**
 * Created by as149 on 12/30/2016.
 */

public class EpsonPrint extends CordovaPlugin {
    private static final String TAG = "WiFiConnectMenu";
    private Thread hThread;
    private Context context;
    private WiFiPort wifiPort;
    private ESCPOSPrinter posPtr;
    private final char ESC = ESCPOS.ESC;
    private final char LF = ESCPOS.LF;
    protected void pluginInitialize() {

       /* context = cordova.getActivity();
        Toast toast = Toast.makeText(context, "pluginInitialize called", Toast.LENGTH_SHORT);
        toast.show();
        wifiPort = WiFiPort.getInstance();
        posPtr = new ESCPOSPrinter();*/
    }

    public void initData(final CallbackContext callbackContext) {

        context = cordova.getActivity();

        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
               /* Toast toast = Toast.makeText(context, "pluginInitialize called", Toast.LENGTH_SHORT);
                toast.show();*/
                wifiPort = WiFiPort.getInstance();
                posPtr = new ESCPOSPrinter();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
            }
        });

    }

    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if(action.equals("initData")) {
            initData(callbackContext);
            return true;
        }
       else if (action.equals("connect")) {

            connect(args.getString(0), callbackContext);
            return true;
        } else if(action.equals("print")) {
                receiptPrint(args.getString(0),callbackContext);
            return true;
        }
        return false;
    }

    private synchronized void connect(final String ip, final CallbackContext callbackContext) {
        {


                    try {
                        if (wifiPort.isConnected()) {
                            wifiDisConn();
                        } else {
                            wifiConn(ip,callbackContext);

                        }
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    } catch (InterruptedException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }

        }
    }

    private void wifiDisConn() throws IOException, InterruptedException
    {
        wifiPort.disconnect();
        hThread.interrupt();
             Toast toast = Toast.makeText(cordova.getActivity(), "Wi-Fi Disconnected", Toast.LENGTH_SHORT);
        toast.show();
    }

    // WiFi Connection method.
    private void wifiConn(String ipAddr,CallbackContext callbackContext) throws IOException
    {
        new connTask(callbackContext).execute(ipAddr);
    }
    // WiFi Connection Task.
    class connTask extends AsyncTask<String, Void, Integer>
    {
        CallbackContext callbackContext;
        connTask(CallbackContext callbackContext){
            this.callbackContext = callbackContext;
        }

        private  ProgressDialog dialog;

        @Override
        protected void onPreExecute()
        {
            cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog = new ProgressDialog(cordova.getActivity());
                    dialog.setTitle("Wi-Fi");
                    dialog.setMessage("Connecting");
                    dialog.show();
                }
            });

        super.onPreExecute();
    }

        @Override
        protected Integer doInBackground(String... params)
        {
            Integer retVal = null;
            try
            {
                // ip
                wifiPort.connect(params[0]);
                retVal = new Integer(0);
            }
            catch (IOException e)
            {
                Log.e(TAG,e.getMessage(),e);
                retVal = new Integer(-1);
            }
            return retVal;
        }

        @Override
        protected void onPostExecute(Integer result)
        {
            if(result.intValue() == 0)
            {
                RequestHandler rh = new RequestHandler();
                hThread = new Thread(rh);
                hThread.start();

                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(dialog.isShowing())
                            dialog.dismiss();
                        Toast toast = Toast.makeText(context, "Wi-Fi Connected", Toast.LENGTH_SHORT);
                        toast.show();
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
                    }
                });

            }
            else
            {
                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(dialog.isShowing())
                            dialog.dismiss();
                        AlertView.showAlert("Wi-Fi Connection Failed",
                                "Check the device status or settings.", context);
                    }
                });

            }
            super.onPostExecute(result);
        }
    }

/*    public void receiptPrint(final String data, final CallbackContext callbackContext)

    {

        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(context, "receiptPrint called", Toast.LENGTH_SHORT);
                toast.show();
                try {
                    posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + "Receipt" + LF + LF);
                    posPtr.printNormal(ESC + "|rA" + ESC + "|bC" + "TEL (123)-456-7890" + LF);
                    posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + "Thank you for coming to our shop!" + LF + LF);

                    posPtr.printNormal("Chicken                   $10.00" + LF);
                    posPtr.printNormal("Hamburger                 $20.00" + LF);
                    posPtr.printNormal("Pizza                     $30.00" + LF);
                    posPtr.printNormal("Lemons                    $40.00" + LF);
                    posPtr.printNormal("Drink                     $50.00" + LF + LF);
                    posPtr.printNormal("Excluded tax             $150.00" + LF);

                    posPtr.printNormal(ESC + "|uC" + "Tax(5%)                    $7.50" + LF);
                    posPtr.printNormal(ESC + "|bC" + ESC + "|2C" + "Total   $157.50" + LF + LF);
                    posPtr.printNormal(ESC + "|bC" + "Payment                  $200.00" + LF);
                    posPtr.printNormal(ESC + "|bC" + "Change                    $42.50" + LF);

                    posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|4C" + "Thank you" + LF);

                    posPtr.lineFeed(3);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));

                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        });
    }*/

    public void receiptPrint(final String data, final CallbackContext callbackContext)
    {
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(context, "receiptPrint called", Toast.LENGTH_SHORT);
                toast.show();
                try {
                    JSONObject jObject = new JSONObject(data);

                    String billType = jObject.getString("bill_type");

                    if (billType.equals("1")) {
                        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("restaurant_name") + LF + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("title") + LF + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + jObject.getString("customer") + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + currentDateTimeString + LF + LF);
                        JSONArray jarray = jObject.getJSONArray("product_detail");
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject jobj = jarray.getJSONObject(i);
                            String name = jobj.getString("name");
                            int nameLegnth = name.length();
                            int count = (26 - nameLegnth);


                            String spaces = String.format("%" + count + "s", "");

                            posPtr.printNormal("#" + (i + 1) + " " + name + " " + jobj.getString("code") + spaces + jobj.getString("quantity") + LF);

                        }


                    }else if(billType.equals("2")) {
                        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("restaurant_name") + LF + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("title") + LF + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + jObject.getString("customer") + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + currentDateTimeString + LF + LF);
                        JSONArray jarray = jObject.getJSONArray("product_detail");
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject jobj = jarray.getJSONObject(i);
                            String name = jobj.getString("name");
                            String cal ="(" + jobj.getString("quantity")+"X"+ jobj.getString("price")+")";
                            int nameLegnth = cal.length();
                            int count = (32 - nameLegnth);
                            String quePrice = jobj.getString("price_qty");
                            int queLength = quePrice.length();
                            count = (count-queLength);




                            String spaces = String.format("%" + count + "s", "");

                            posPtr.printNormal("#" + (i + 1) + " " + name + " " + jobj.getString("code") +"\n" +
                                    cal+ spaces+jobj.getString("price_qty")+ LF);

                        }


                        posPtr.printNormal(ESC + "|bC" + "Total                    "+jObject.getString("total") + LF);
                        posPtr.printNormal(ESC + "|bC" + "Items                    "+jObject.getString("items")+"("+ jObject.getString("itemcount")+")"+ LF);
                        posPtr.printNormal(ESC + "|bC" + "Order Tax                "+ jObject.getString("ordertax") + LF);
                        posPtr.printNormal(ESC + "|bC" + "Toatal Payable           "+ jObject.getString("total_payble") + LF);



                    } else if(billType.equals("3")) {
                        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("restaurant_name") + LF + LF);

                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("address") + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("telphone") + LF+ LF);


                        posPtr.printNormal("Reffrence No. " +jObject.getString("reference_no") + LF);
                        posPtr.printNormal(jObject.getString("table_name") + LF);
                        posPtr.printNormal(jObject.getString("restaurant_name") + LF);
                        posPtr.printNormal("Customer " +jObject.getString("customer") + LF);
                        posPtr.printNormal("Date " +currentDateTimeString + LF+ LF);

                        JSONArray jarray = jObject.getJSONArray("product_detail");
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject jobj = jarray.getJSONObject(i);
                            String name = jobj.getString("name");
                            String tx = jobj.getString("tax_name");

                            int nameLegnth = name.length();
                            int count = (28 - nameLegnth);
              /*              String quePrice = jobj.getString("price_qty");
                            int queLength = quePrice.length();
                            count = (count-queLength);*/






                            String spaces = String.format("%" + (count-tx.length()) + "s", "");

                            posPtr.printNormal("#" + (i + 1) + " " + name + " " + spaces+"" +tx+ LF);

                            String cal =jobj.getString("quantity")+"X"+ jobj.getString("price")+"("+jobj.getString("price_qty")+"+"+jobj.getString("tax_amount")+")";
                            String price = jobj.getString("price_tax");

                            int count1 = (32 - (cal.length()+price.length()));
                            String spaces1 = String.format("%" + count1 + "s", "");





                            posPtr.printNormal(cal +spaces1 + price+ LF);

                        }


                        posPtr.printNormal(ESC + "|bC" + "Total                    "+jObject.getString("total") + LF);
                        posPtr.printNormal(ESC + "|bC" + "Tax                    "+jObject.getString("tax")+ LF);
                        posPtr.printNormal(ESC + "|bC" + "Rounding                "+ jObject.getString("rounding") + LF);
                        posPtr.printNormal(ESC + "|bC" + "Grand total                "+ jObject.getString("grand_total") + LF);
                        posPtr.printNormal(ESC + "|bC" + "Paid by           "+ jObject.getString("paid_by") + LF);
                        posPtr.printNormal(ESC + "|bC" + "Change           "+ jObject.getString("change") + LF+ LF);
                        posPtr.printNormal(jObject.getString("footer_data") +LF);



                    }else if(billType.equals("0")) {
                        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());

                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + "Rajeev Restaurant" + LF + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("title") + LF + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + jObject.getString("customer") + LF);
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + currentDateTimeString + LF + LF);
                        JSONArray jarray = jObject.getJSONArray("product_detail");
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject jobj = jarray.getJSONObject(i);
                            String name = jobj.getString("name");
                            int nameLegnth = name.length();
                            int count = (19 - nameLegnth);


                            String spaces = String.format("%" + count + "s", "");

                            posPtr.printNormal("#" + (i + 1) + " " + name + " " + jobj.getString("code") + spaces + jobj.getString("quantity") + LF);

                        }


                    } else {

                        Toast toast1 = Toast.makeText(context, "Going in else", Toast.LENGTH_SHORT);
                        toast1.show();

                   /* posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + "Receipt" + LF + LF);
                    posPtr.printNormal(ESC + "|rA" + ESC + "|bC" + "TEL (123)-456-7890" + LF);
                    posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + "Thank you for coming to our shop!" + LF + LF);*/
                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|2C" + jObject.getString("Title") + LF + LF);
                        posPtr.printNormal(ESC + "|rA" + ESC + "|bC" + "Address " + jObject.getString("Address") + LF);
                        posPtr.printNormal(ESC + "|rA" + ESC + "|bC" + "Reffrence " + jObject.getString("Refrense") + LF);
                        //posPtr.printNormal(ESC + ESC + jObject.getString("Title") + LF + LF);
                        //posPtr.printNormal(ESC + "Address " + jObject.getString("Address") + LF + LF);
                        //posPtr.printNormal(ESC + "Reffrence " + jObject.getString("Refrense") + LF + LF);

                        JSONArray jarray = jObject.getJSONArray("ProductDetail");
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject jobj = jarray.getJSONObject(i);



                            posPtr.printNormal(jobj.getString("Title") + "                   " + jobj.getString("Value") + LF);

                        }


                        //  posPtr.printNormal(ESC + "Total: " + jObject.getString("Total") + LF + LF);
                        posPtr.printNormal(ESC + "|bC" + ESC + "|2C" + "Total   " + jObject.getString("Total") + LF + LF);
                        posPtr.printNormal(ESC + "|bC" + ESC + "|2C" + "Tax   " + jObject.getString("Tax") + LF + LF);
                        posPtr.printNormal(ESC + "|bC" + ESC + "|2C" + "GrantTotal   " + jObject.getString("GrantTotal") + LF + LF);
                        // posPtr.printNormal(ESC + "Tax: " + jObject.getString("Tax") + LF + LF);
                   /* posPtr.printNormal("Chicken                   $10.00" + LF);
                    posPtr.printNormal("Hamburger                 $20.00" + LF);
                    posPtr.printNormal("Pizza                     $30.00" + LF);
                    posPtr.printNormal("Lemons                    $40.00" + LF);
                    posPtr.printNormal("Drink                     $50.00" + LF + LF);
                    posPtr.printNormal("Excluded tax             $150.00" + LF);

                    posPtr.printNormal( ESC + "|uC" + "Tax(5%)                    $7.50" + LF);
                    posPtr.printNormal( ESC + "|bC" + ESC + "|2C" + "Total   $157.50" + LF + LF);
                    posPtr.printNormal( ESC + "|bC" + "Payment                  $200.00" + LF);
                    posPtr.printNormal( ESC + "|bC" + "Change                    $42.50" + LF);*/

                        posPtr.printNormal(ESC + "|cA" + ESC + "|bC" + ESC + "|4C" + "Thank you" + LF);
                    }

                    posPtr.lineFeed(3);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
                } catch (IOException e)
                {
                    Log.e(TAG,e.getMessage(),e);
                    Toast toast1 = Toast.makeText(context, "OTHER EXCEPTION"+e.getMessage(), Toast.LENGTH_SHORT);
                    toast1.show();
                } catch (JSONException e) {
                    Toast toast1 = Toast.makeText(context, "JSON EXCEPTION"+e.getMessage(), Toast.LENGTH_SHORT);
                    toast1.show();
                    e.printStackTrace();
                }

            }
        });



    }

}
