package com.maxmoney.maxcddconsole.Activity;

import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Header;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.maxmoney.maxcddconsole.Adapter.TopUpLedgerAdapter;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
import com.maxmoney.maxcddconsole.Connectivity.BasedUrl;
import com.maxmoney.maxcddconsole.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static android.os.Environment.DIRECTORY_DCIM;
import static com.android.volley.Request.Method.GET;
import static com.android.volley.Request.Method.POST;

public class TopupLedgerActivity extends AppCompatActivity implements AbsListView.OnScrollListener{

    ListView list;
    String session;
    StandardProgressDialog standardProgressDialog;

    private ArrayList<Map<String, String>> data = null;
    private TopUpLedgerAdapter mPLAdapter;
    private int currentPagination = 1;
    private int total = 100;
    TextView textView_downloadSUmmary;
    DownloadManager downloadManager;
    ImageView imageView_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topup_ledger);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        session = getIntent().getStringExtra("session");
        standardProgressDialog = new StandardProgressDialog(this.getWindow().getContext());
        list = findViewById(R.id.listView);
        textView_downloadSUmmary = findViewById(R.id.textView_downloadSUmmary);
        imageView_back = findViewById(R.id.imageView_back);

        standardProgressDialog.show();
        getTotalTopap();

        textView_downloadSUmmary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                standardProgressDialog.show();
                downloadFile();
            }
        });

        imageView_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (totalItemCount >0 && list != null) {
            int lastPosition = list.getLastVisiblePosition();
            if (lastPosition + 1 == totalItemCount && data.size() < total) {

                Log.d("data", String.valueOf(data.size()));
                Log.d("data", String.valueOf(total));
                currentPagination++;
                getDetailsTopap();
            }
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    private void getTotalTopap() {
        data = new ArrayList<Map<String, String>>(); // data
        mPLAdapter = new TopUpLedgerAdapter(getApplicationContext(), data);
        list.setAdapter(mPLAdapter);
        list.setOnScrollListener(this);
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"topup/my-ledger",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj1 = new JSONObject(response);
                            total = Integer.parseInt(obj1.getString("total"));
                            Log.d("total data omoe", String.valueOf(total));
                            getDetailsTopap();
                            standardProgressDialog.dismiss();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Please check Internet Connection !!", Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }

    private void getDetailsTopap() {
        StringRequest stringRequest = new StringRequest(GET,  BasedUrl.URL_STAGING +"topup/my-ledger?page="+currentPagination,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            Log.d("response",response);
                            JSONObject obj1 = new JSONObject(response);
                            JSONArray array = obj1.getJSONArray("entries");
                            for(int i = 0; i< array.length(); i++){
                                JSONObject product = array.getJSONObject(i);

                                double profit = 0.0;

                                if(product.has("retailPrice")){
                                    if(!product.getString("retailPrice").equals("") && !product.getString("agentPrice").equals("")){
                                        profit = Double.parseDouble(product.getString("retailPrice")) - Double.parseDouble(product.getString("agentPrice"));
                                    }
                                }



                                Map<String, String> addData = new HashMap<String, String>();
                                addData.put("msg1", "MOBILE NO :"+product.getString("mobileNo"));
                                addData.put("msg2", product.getString("status"));
                                addData.put("msg3", product.getString("country"));
                                addData.put("msg4", product.getString("product"));
                                addData.put("msg5", product.getString("debit"));
                                addData.put("msg6", "RM "+product.getString("balance"));
                                addData.put("msg7", String.format("%.3f",profit));
                                addData.put("msg8", product.getString("time"));
                                addData.put("msg9", product.getString("description"));
                                data.add(addData);
                            }
                            mPLAdapter.refreshData(data);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Please check Internet Connection !!", Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

    }

    private void downloadFile(){
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse("https://www.maxmoney.com/my/app/android/excel.php?api-key="+session);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        Long reference = downloadManager.enqueue(request);

        standardProgressDialog.dismiss();
        Toast.makeText(getApplicationContext(),"File download",Toast.LENGTH_SHORT).show();
    }
}
