package com.sendsms.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.sendsms.Parsing.MessageParsing;
import com.sendsms.R;
import com.sendsms.adapter.GetAllDataAdapter;
import com.sendsms.model.MessageDetails;
import com.sendsms.utills.Util;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class SmsDetailsActivity extends AppCompatActivity implements View.OnClickListener {

    Context mContext;
    GridView message_list;
    ArrayList<MessageDetails> messageDetails = new ArrayList<>();
    GetAllDataAdapter mGetAllDataAdapter;
    Button sendAll;
    TextView tv_caption;
    public String URL = "", Caption = "";


    int counter = 0;
    int messageSize = 0;

    PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_details);

        initializeView();
    }

    public void initializeView() {

        mContext = this;

        try {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                URL = bundle.getString("url");
                Caption = bundle.getString("caption");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        message_list = (GridView) findViewById(R.id.message_list);
        tv_caption = (TextView) findViewById(R.id.tv_caption);
        sendAll = (Button) findViewById(R.id.sendAll);

        tv_caption.setText("" + Caption);

        sendAll.setOnClickListener(this);

        message_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                int pos = position + 1;

                sendSMS(messageDetails.get(position).getNumber(), messageDetails.get(position).getMessage(), pos);
            }
        });


        if (Util.isNetworkAvailable(getApplicationContext())) {
            new GetAllMessageListTask(URL).execute();
        } else {
            Util.customDialog(getApplicationContext(), "No Network Connection ");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sendAll: {

                if (messageDetails.size() > 0) {
                    messageSize = messageDetails.size();
                    for (int i = 0; i < messageDetails.size(); i++) {

                        String number = messageDetails.get(i).getNumber();
                        String message = messageDetails.get(i).getMessage();

                        int pos = i + 1;
                        sendSMS(number, message, pos);
                    }


                }

                break;
            }
        }
    }


    private void sendSMS(String phoneNumber, String message, final int pos) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0, new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:

                        Toast.makeText(mContext, "Message successfully sent " + pos, Toast.LENGTH_SHORT).show();

                        counter++;

                        try {
                            if (messageSize == counter)
                            {
                                View popupView = LayoutInflater.from(mContext).inflate(R.layout.dialog_under_development, null);
                                popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

                                popupWindow.setAnimationStyle(R.style.DialogAnimation);
                                popupWindow.setContentView(popupView);
                                popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);

                                LinearLayout popup_element = (LinearLayout) popupView.findViewById(R.id.popup_element);

                                popup_element.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        popupWindow.dismiss();
                                    }
                                });
                            }
                        }catch (Exception e)
                        {
                            e.printStackTrace();
                        }



                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(mContext, "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(mContext, "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(mContext, "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(mContext, "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(mContext, "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(mContext, "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }


    private class GetAllMessageListTask extends AsyncTask<Void, Void, Object[]> {

        String mUrl = "";

        public GetAllMessageListTask(String url) {
            this.mUrl = url;
        }

        @Override
        public void onPreExecute() {
            Util.showProDialog(mContext);
        }

        @Override
        protected Object[] doInBackground(Void... params) {
            // TODO Auto-generated method stub
            return MessageParsing.getAllMessageDetails(mUrl);
        }

        @Override
        public void onPostExecute(Object[] result) {
            Util.dismissDialog();
            try {
                boolean status = (Boolean) result[0];
                if (result != null && status) {

                    messageDetails = (ArrayList<MessageDetails>) result[1];

                    if (messageDetails.size() > 0) {
                        mGetAllDataAdapter = new GetAllDataAdapter(mContext, messageDetails);
                        message_list.setAdapter(mGetAllDataAdapter);
                    } else {

                        mGetAllDataAdapter = new GetAllDataAdapter(mContext, messageDetails);
                        message_list.setAdapter(mGetAllDataAdapter);
                    }
                } else {
                    Util.customDialog(mContext, "Result not found");

                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        }
    }
}
