package com.example.apidemo;

import in.shoppingwish.scandid.net.Constants;
import in.shoppingwish.scandid.net.JSONConstants;
import in.shoppingwish.scandid.net.LocalSearchResult;
import in.shoppingwish.scandid.net.Product;
import in.shoppingwish.scandid.net.ScandidRequestHandler;
import in.shoppingwish.scandid.net.SearchResult;

import java.io.InputStream;
import java.net.URL;

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

import com.example.apidemo.MainActivity.LongOperation1;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ResultActivity extends Activity{

	Product product;
	Bitmap bitmap;
	ScandidRequestHandler scandidRequestHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		scandidRequestHandler =  new ScandidRequestHandler(CConstants.API_KEY);
		setContentView(R.layout.result1);
		product = (Product)getIntent().getSerializableExtra("Product");
		if(product.get_productResponseMessage().equals("error") || product.get_productResponseMessage().equals("Not available"))
		{
			((TextView)findViewById(R.id.textView1)).setText(product.get_productResponseMessage());
		}
		else if(product.get_productResponseMessage().equals(JSONConstants.RESPONSE_SUCCESS))
		{
			
			((TextView)findViewById(R.id.textView1)).setText(product.get_productTitle());
			String text = "<font color=#a1a1a1>"+"Lowest Price:"+"</font> <font color=#ff751b>"+("Rs. "+product.get_productLowestPrice())+"</font>";
			if(product.get_productLowestPrice().toString().equals("0"))
			((TextView)findViewById(R.id.TextView01)).setText("Out of stock");
			else
			((TextView)findViewById(R.id.TextView01)).setText(Html.fromHtml(text));
			int numberOfInstockStores = product.get_productTotalNumberOfStore();
			((TextView)findViewById(R.id.TextView02)).setText("Available from "+numberOfInstockStores+" stores");
			new LongOperation2().execute("");
			

		}
	}
	public void launchLocalSearch(View v)
	{
		new LongOperation1().execute("");
	}
	class LongOperation2 extends AsyncTask<String, Void, String> {
		//ProgressDialog progress;
		Drawable d;
		@Override
		protected String doInBackground(String... params) {
			try{
	        	URL url = new URL(product.get_productImageURL());
	        	InputStream content = (InputStream)url.getContent();
	        	 d = Drawable.createFromStream(content , "src");
	        	 bitmap = ((BitmapDrawable)d).getBitmap();
	        	//bitmap = getResizedBitmap(bitmap,150,120);
	        	//d = new BitmapDrawable(getResources(),bitmap);
			}catch(Exception e){}


			return "";
		}


		@Override
		protected void onPostExecute(String result) {
			//progress.dismiss();
			try {
				if(d == null)
				{
					d = getResources().getDrawable(R.drawable.imgntfound);
					bitmap = ((BitmapDrawable)d).getBitmap();
				}
				if(d !=null && bitmap!=null)
				{
					((ImageView)findViewById(R.id.imageView1)).setImageDrawable(d);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
	
	 class LongOperation1 extends AsyncTask<String, Void, LocalSearchResult> {
	    	ProgressDialog progress;

	        @Override
	        protected LocalSearchResult doInBackground(String... params) {
	        	LocalSearchResult searchResult = null;
	        	
				try {
				 searchResult = scandidRequestHandler.getLocalSearchResult("",product.get_productID(),"12.9699", "77.6499");
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return searchResult;
	        }

	        @Override
	        protected void onPostExecute(LocalSearchResult searchResult) {
	        	
	        	progress.dismiss();
	        	if(searchResult !=null && (!searchResult.get_localSearchResponseMessage().equals(JSONConstants.RESPONSE_ERROR)))
	        	{
	        		Intent intent = new Intent(getApplicationContext(),LocalResultListActivity.class);
		        	intent.putExtra("SearchResult", searchResult); 
		        	startActivity(intent);
	        	}
	        	else
					Toast.makeText(
							getApplicationContext(),
							"Either you are not contected to internet or server is down try again later.",
							Toast.LENGTH_LONG).show();
	        	
	        	
	        	
	        }

	        @Override
			protected void onPreExecute() {
				progress = ProgressDialog.show(ResultActivity.this, "Hang on",
						"Searching barcodes...", true,true,new DialogInterface.OnCancelListener(){
	                @Override
	                public void onCancel(DialogInterface dialog) {
	                	LongOperation1.this.cancel(true);
	                }
	            });
			}

	        @Override
	        protected void onProgressUpdate(Void... values) {}

			

			
	    }
	

}
