package com.sendsms.fragment;

import android.annotation.SuppressLint;
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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
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;

/**
 * Created by hemants on 6/29/2016.
 */
@SuppressLint("ValidFragment")
public class FragmentDetails extends Fragment implements View.OnClickListener{

    Context mContext;
    View rootView;
    GridView message_list;

    ArrayList<MessageDetails> messageDetails = new ArrayList<>();
    GetAllDataAdapter mGetAllDataAdapter;
    Button sendAll;

    @SuppressLint("ValidFragment")
    public FragmentDetails(Context context) {
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_details, container, false);

        initializeView();

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

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

        return rootView;
    }


    public void initializeView() {

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

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

        sendAll.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == sendAll)
        {
         if (messageDetails.size()>0)
         {
             for (int i = 0; i < messageDetails.size(); i++) {
                 String number = messageDetails.get(i).getNumber();
                 String message = messageDetails.get(i).getMessage();

                 sendSMS(number, message);
             }
         }
        }
    }

    private void sendSMS(String phoneNumber, String message) {
        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---
        getActivity().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(mContext, "Message successfully sent",
                                Toast.LENGTH_SHORT).show();
                        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---
        getActivity().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[]> {

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

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

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

        }
    }
}
