package com.maxmoney.maxcddconsole.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
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.ActivityV2.TopapActivityV2;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
import com.maxmoney.maxcddconsole.Connectivity.BasedUrl;
import com.maxmoney.maxcddconsole.R;

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

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

import static com.android.volley.Request.Method.DELETE;
import static com.android.volley.Request.Method.GET;
import static com.android.volley.Request.Method.POST;

public class DashboardActivity extends AppCompatActivity implements View.OnClickListener {

    String session = "",user_role = "",email ="";
    StandardProgressDialog standardProgressDialog;
    LinearLayout linear_balance;
    TextView textView_balance,textView_title;

    Button button_logout;
    LinearLayout linear_customer_main,linear_topap_main,linear_complience;
    LinearLayout linear_customer_all,linear_cdd,linear_user_all,linear_topap,linear_approve,linear_user_search_c;
    TextView textView_topap_ledger,textView_paySlip;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        standardProgressDialog = new StandardProgressDialog(this.getWindow().getContext());
        session = getIntent().getStringExtra("session");

        textView_balance = findViewById(R.id.textView_balance);
        textView_title = findViewById(R.id.textView_title);
        standardProgressDialog.show();
        button_logout = findViewById(R.id.button_logout);
        textView_topap_ledger = findViewById(R.id.textView_topap_ledger);
        textView_paySlip = findViewById(R.id.textView_paySlip);

        linear_customer_main = findViewById(R.id.linear_customer_main);
        linear_topap_main = findViewById(R.id.linear_topap_main);
        linear_complience = findViewById(R.id.linear_complience);
        linear_balance = findViewById(R.id.linear_balance);

        linear_customer_all = findViewById(R.id.linear_customer_all);
        linear_cdd = findViewById(R.id.linear_cdd);
        linear_user_all = findViewById(R.id.linear_user_all);
        linear_topap = findViewById(R.id.linear_topap);
        linear_approve = findViewById(R.id.linear_approve);
        linear_user_search_c = findViewById(R.id.linear_user_search_c);

        button_logout.setOnClickListener(this);
        linear_topap.setOnClickListener(this);
        linear_approve.setOnClickListener(this);
        linear_customer_all.setOnClickListener(this);  //REGISTER CUSTOMER
        linear_cdd.setOnClickListener(this); // CDD SEARCH
        linear_user_all.setOnClickListener(this); //USER SEARCH
        linear_user_search_c.setOnClickListener(this); //USER SEARCH
        textView_topap_ledger.setOnClickListener(this); //TOPAP LEDGER
        textView_paySlip.setOnClickListener(this); //PAYSLIP
        getUserDetails();


    }

    public void getUserDetails(){
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"sessions/current",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        standardProgressDialog.dismiss();
                        try {
                            JSONObject obj = new JSONObject(response);
                            if(obj.has("role")){
                                user_role = obj.getString("role");
                                email = obj.getString("username");
                                textView_title.setText(obj.getString("username")+" / "+obj.getString("role"));
                                if(user_role.equals("maxCddOfficer") || user_role.equals("cddOfficer") || user_role.equals("complianceManager")){
                                    if(user_role.equals("maxCddOfficer") || user_role.equals("cddOfficer") || user_role.equals("maxAgents")){
                                        linear_complience.setVisibility(View.GONE);
                                        getTopapBalance();
                                    }else if(user_role.equals("complianceManager")){
                                        linear_customer_main.setVisibility(View.GONE);
                                        linear_balance.setVisibility(View.GONE);
                                        linear_topap_main.setVisibility(View.GONE);
                                    }
                                }else{
                                    Toast.makeText(getApplicationContext(),"Cannot use "+user_role.toString().toUpperCase()+" ID",Toast.LENGTH_LONG).show();
                                    Intent next = new Intent(getApplicationContext(),LoginActivity.class);
                                    startActivity(next);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                        parseVolleyError(error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }

            @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);
    }

    public void parseVolleyError(VolleyError error) {
        try {
            String responseBody = new String(error.networkResponse.data, "utf-8");
            JSONObject data = new JSONObject(responseBody);
            if(data.has("message")){
                Toast.makeText(getApplicationContext(), data.getString("message"),Toast.LENGTH_SHORT).show();
                Intent next = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(next);
            }else{
                Toast.makeText(getApplicationContext(),"Login error",Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
        } catch (UnsupportedEncodingException errorr) {
        }
    }

    public void getTopapBalance(){
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"topup/accounts/account/"+email,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            if(obj.has("balance")){
                               textView_balance.setText("RM "+obj.getString("balance"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        parseVolleyError(error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }

            @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);
    }
    @Override
    public void onBackPressed() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case  R.id.button_logout: {
                logout();
                break;
            }
            case R.id.linear_topap : {
                Intent next = new Intent(getApplicationContext(), TopapActivityV2.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.linear_approve: {
                Intent next = new Intent(getApplicationContext(), ApproveActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.linear_customer_all: {
                Intent next = new Intent(getApplicationContext(), RegistrationActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.linear_cdd: {
                Intent next = new Intent(getApplicationContext(), CddSearchActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.linear_user_search_c: {
                Intent next = new Intent(getApplicationContext(),UserSearchActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.linear_user_all: {
                Intent next = new Intent(getApplicationContext(),UserSearchActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.textView_topap_ledger:{
                Intent next = new Intent(getApplicationContext(),TopupLedgerActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

            case R.id.textView_paySlip:{
                Intent next = new Intent(getApplicationContext(),PaySlipActivity.class);
                next.putExtra("session",session);
                startActivity(next);
                break;
            }

        }
    }

    public void logout(){
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Log Out Activity")
                .setMessage("Are you sure you want to log out ?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        killSession();
                        Intent next = new Intent(getApplicationContext(),LoginActivity.class);
                        startActivity(next);
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }

    private void killSession() {
        StringRequest stringRequest = new StringRequest(DELETE, BasedUrl.URL_STAGING +"sessions/current",
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if(response.equals("")){
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @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);
    }
}
