package pkg.DestMsgs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.*;

import pkg.DestMsgs.R.drawable;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ReadMessages extends ListActivity {
	TextView tvCntryTitle = null;
	ImageView ivFrmFlag = null;
	Button btnAboutTab = null;
	Button btnTourInfoTab = null;
	Button btnPicturesTab = null;
	Button btnMoreTab = null;
	Button btnBack = null;
	OnClickListener tabListener = null;
	
    private ProgressDialog m_ProgressDialog = null; 
    private ArrayList<PostMessage> m_PostMessages = null;
    static PostMessageAdapter m_adapter;
    private Runnable viewPostMessages;
    ArrayAdapter<String> adapter = null;
    ArrayList<String> data = new ArrayList<String>();
    
    LayoutInflater vi;
    View v;
    TextView tvMsgName;
    TextView tvMsgDate;
    TextView tvMsgPost;
    ListView lv;
    Button btnDesc = null;
    Button btnAsc = null;
    Bundle myBundle = null;
    static String result = "";
    static URL url = null;
    Button btnMsgImage;
    boolean once = true;
    public static HashMap<Integer, Bitmap> hmImages;
    public static Bitmap MsgImage;
    ListView lvMsgs;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.readmsgs);
        
        tvCntryTitle = (TextView)findViewById(R.id.cntryTitleReadMsgs);
        tvCntryTitle.setText(Constants.Country);
        ivFrmFlag = (ImageView)findViewById(R.id.frmFlagReadMsgs);
        int resId;
        if(Constants.CountryCode.equals("do"))
        	resId = getResources().getIdentifier("do_flag", "drawable", "pkg.DestMsgs");
        else
        	resId = getResources().getIdentifier(Constants.CountryCode, "drawable", "pkg.DestMsgs");
        if(resId == 0)
        	resId = getResources().getIdentifier(Constants.DefaultImage, "drawable", "pkg.DestMsgs");
        ivFrmFlag.setBackgroundResource(resId);
        
        tabListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(((Button)v).getId() == R.id.btnAboutTab)
					TabActivityDemo.SwitchTab(0);
				else if(((Button)v).getId() == R.id.btnTourInfoTab)
					TabActivityDemo.SwitchTab(1);
				else if(((Button)v).getId() == R.id.btnPicturesTab)
					TabActivityDemo.SwitchTab(2);
				else if(((Button)v).getId() == R.id.btnMoreTab)
					TabActivityDemo.SwitchTab(3);
				
				finish();
			}
		};
		
		
		m_PostMessages = new ArrayList<PostMessage>();
        this.m_adapter = new PostMessageAdapter(this, R.layout.messagerow, m_PostMessages);
        setListAdapter(this.m_adapter);

        
        viewPostMessages = new Runnable(){
            public void run() {
                getPostMessages();
            }
        };
        
        Thread thread =  new Thread(null, viewPostMessages, "MagentoBackground");
        thread.start();
        m_ProgressDialog = ProgressDialog.show(ReadMessages.this,    
              "Please wait...", "Retrieving data ...", true);
        

        
        btnAboutTab = (Button) findViewById(R.id.btnAboutTab);
        btnAboutTab.setOnClickListener(tabListener);
        
        btnTourInfoTab = (Button) findViewById(R.id.btnTourInfoTab);
        btnTourInfoTab.setOnClickListener(tabListener);
        
        btnPicturesTab = (Button) findViewById(R.id.btnPicturesTab);
        btnPicturesTab.setOnClickListener(tabListener);
        
        btnMoreTab = (Button) findViewById(R.id.btnMoreTab);
        btnMoreTab.setOnClickListener(tabListener);
      
        btnBack = (Button) findViewById(R.id.btnBackReadMsgs);
        btnBack.setOnClickListener(tabListener);
        
        Button lvMsg = (Button)findViewById(R.id.btnLeaveMsgsRM);
        lvMsg.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		    	Intent i = new Intent(getApplicationContext(), LeaveMessage.class);
				startActivity(i);
			}
		});
        
        
    }
    
    private Runnable returnRes = new Runnable() {

        public void run() {
            if(m_PostMessages != null && m_PostMessages.size() > 0){
                m_adapter.notifyDataSetChanged();
                for(int i=0;i<m_PostMessages.size();i++)
                m_adapter.add(m_PostMessages.get(i));
            }
            m_ProgressDialog.dismiss();
            m_adapter.notifyDataSetChanged();
        }
    };
    
    private void getPostMessages(){
    	
    	HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        //String url = "http://www.junesoftware.com/iphone/destmsg/ReceiveMessages.aspx?cCode="+Constants.CountryCode;
        HttpGet httpGet = new HttpGet(Constants.ReadURL + "?cCode="+Constants.CountryCode);
    	
        try{
        	HttpResponse res = httpClient.execute(httpGet, localContext);
			HttpEntity he = res.getEntity();
			InputStream is = he.getContent();
			
        	BufferedReader br = new BufferedReader(new InputStreamReader(is));
		   	String s = new String();
//		   	while((s += br.readLine())!=null){
//		   		 br.readLine();
//		   	}
		   	
		   	while(true){
		   		String str = new String();
		   		str = br.readLine();
		   		if(str == null)
		   			break;
		   		s +=  str + "<cr>";
		   	}
		   	s = s.replaceAll("'", "<aps>");
			JSONObject json = new JSONObject(s.toString());
			JSONArray jmsgarr = json.getJSONArray("messages");
			m_PostMessages = new ArrayList<PostMessage>();
			hmImages = new HashMap<Integer, Bitmap>();
			for(int i = 0; i<jmsgarr.length();i++)
			{
				JSONObject one = jmsgarr.getJSONObject(i);
			    PostMessage pm = new PostMessage();				
				pm.setMsgName(one.get("name").toString());
				pm.setMsgDate(one.get("date").toString());
				String a = one.get("post").toString().replaceAll("<aps>", "'").replaceAll("<cr>", "\n");
				pm.setMsgPost(a);
				
				pm.setMsgId(Integer.parseInt(one.get("msgid").toString()));
				pm.setImgCount(Integer.parseInt(one.get("imgCount").toString()));
				
//				if(pm.getImgCount() == 1){			
//					pm.setMsgImg(getMsgImage(pm.getMsgId(),pm.getImgCount()));
//					hmImages.put(new Integer(pm.getMsgId()), pm.getMsgImg());
//				}
				
				if(pm.getImgCount() == 1){
					ReadImageThread  rit = new ReadImageThread(pm.getMsgId());
//					rit.t.join();
//					m_adapter.notifyDataSetChanged();
				}		

				m_PostMessages.add(pm);
				
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	   	
        runOnUiThread(returnRes);
    }
    
    ///////////////////////////
   public Bitmap getMsgImage(int msgId,int imgCount){
	   Bitmap bm = null ;
		try {
			url = new URL(Constants.ReadURL + "?msgid="+msgId);
		} catch (MalformedURLException e) {
			e.printStackTrace(System.out);
			//Log.e(e.getMessage());
		} 

		if (url != null) {
			try {
				HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
				InputStream ins = urlConn.getInputStream();

				BitmapFactory.Options options=new BitmapFactory.Options();
				options.inSampleSize = 8;
				Rect re = new Rect(0,0,320,320);
				bm = BitmapFactory.decodeStream(ins,re,options);
				
				ins.close();
				urlConn.disconnect();

			} catch (IOException e) {
				e.printStackTrace(System.out);
				//Log.e(e.getMessage());
			}
			
		}
		return bm;
   }
    ///////////////////////////
    
    private class PostMessageAdapter extends ArrayAdapter<PostMessage> {
        @SuppressWarnings("unused")
    	private ArrayList<PostMessage> items;

        public PostMessageAdapter(Context context, int textViewResourceId, ArrayList<PostMessage> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                v = convertView;
                if (v == null) {
                    vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.messagerow, null);
                }
                //PostMessage o = items.get(position);
                PostMessage o  = getItem(position);
                
                if (o != null) {
                        tvMsgName = (TextView) v.findViewById(R.id.MsgName);
                        tvMsgDate = (TextView) v.findViewById(R.id.MsgDate);
                        tvMsgPost = (TextView)v.findViewById(R.id.MsgPost);
                        btnMsgImage = (Button) v.findViewById(R.id.btnMsgImage);
                        if (tvMsgName != null) {
                              tvMsgName.setText(o.getMsgName());
                        }
                        if(tvMsgDate != null){
                              tvMsgDate.setText(o.getMsgDate());
                        }
                        if(tvMsgPost != null){
                            tvMsgPost.setText(o.getMsgPost());
                        }
                        BitmapDrawable bmd;
                        if(btnMsgImage != null &&  o.getImgCount() == 1){
                        	bmd = new BitmapDrawable(hmImages.get(o.getMsgId()));
                        	btnMsgImage.setVisibility(View.VISIBLE);
                        	btnMsgImage.setBackgroundDrawable(bmd);
	                        btnMsgImage.setText(new Integer(o.getMsgId()).toString());
	                        btnMsgImage.setTextSize(1);
	                        btnMsgImage.setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									MsgImage = hmImages.get(Integer.parseInt(((Button)v).getText().toString()));
			                        Intent i = new Intent(getApplicationContext(), ImageActivity.class);
									startActivity(i);
								}
							});
                        }
                        else{
                            btnMsgImage.setVisibility(View.GONE);
                    	}
                        	
                        	
                }

                return v;
        }
    }

}