package com.example.apidemo;



import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONObject;




import in.shoppingwish.scandid.net.Constants;
import in.shoppingwish.scandid.net.JSONConstants;
import in.shoppingwish.scandid.net.Product;
import in.shoppingwish.scandid.net.ScandidRequestHandler;
import in.shoppingwish.scandid.net.SearchResult;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.android.CameraTest.ZBarConstants;
import net.sourceforge.zbar.android.CameraTest.CameraTestActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int ZBAR_SCANNER_REQUEST = 0;
    private static final int ZBAR_QR_SCANNER_REQUEST = 1;
    String resultLink;
    ScandidRequestHandler scandidRequestHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scandidRequestHandler =  new ScandidRequestHandler(CConstants.API_KEY);
    }

    public void launchScanner(View v) {
        if (isCameraAvailable()) {
            Intent intent = new Intent(this, CameraTestActivity.class);
            startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
            
        } else {
            Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
        }
    	
    }
    public void launchSearch(View v) {
    	if(((EditText)findViewById(R.id.editText1)).getText().toString().length()>0)
    	{
    		new LongOperation1().execute("");
    	}
    }
    public void launchQRScanner(View v) {
        if (isCameraAvailable()) {
            Intent intent = new Intent(this, CameraTestActivity.class);
            intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.EAN13});
            startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
            
        } else {
            Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
        }
    }
    public void luanchQRLink(View v) {

    }

    public boolean isCameraAvailable() {
        PackageManager pm = getPackageManager();
        return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ZBAR_SCANNER_REQUEST:
            case ZBAR_QR_SCANNER_REQUEST:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
                    resultLink = data.getStringExtra(ZBarConstants.SCAN_RESULT);
                    new LongOperation().execute("");
                    
                } else if(resultCode == RESULT_CANCELED && data != null) {
                    String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
                    if(!TextUtils.isEmpty(error)) {
                        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    	
    	
    }
    class LongOperation extends AsyncTask<String, Void, Product> {
    	ProgressDialog progress;

        @Override
        protected Product doInBackground(String... params) {
        	Product product = null;
        	
			try {

				product = scandidRequestHandler.getProductDetailsFromBarcode(resultLink);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return product;
        }

        @Override
        protected void onPostExecute(Product product) {
        	progress.dismiss();
        	if(product != null && (!product.get_productResponseMessage().equals(JSONConstants.RESPONSE_ERROR)))
        	{
	        	Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
	        	intent.putExtra("Product", product); 
	        	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(MainActivity.this, "Hang on",
					"Searching barcodes...", true,true,new DialogInterface.OnCancelListener(){
                @Override
                public void onCancel(DialogInterface dialog) {
                	LongOperation.this.cancel(true);
                }
            });
		}

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

		

		
    }
    class LongOperation1 extends AsyncTask<String, Void, SearchResult> {
    	ProgressDialog progress;

        @Override
        protected SearchResult doInBackground(String... params) {
        	SearchResult searchResult = null;
        	
			try {
			 searchResult = scandidRequestHandler.getSearchResult(((EditText)findViewById(R.id.editText1)).getText().toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return searchResult;
        }

        @Override
        protected void onPostExecute(SearchResult searchResult) {
        	progress.dismiss();
        	if(searchResult != null && (!searchResult.get_searchResponseMessage().equals(JSONConstants.RESPONSE_ERROR)))
        	{
	        	Intent intent = new Intent(getApplicationContext(),ResultListActivity.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(MainActivity.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) {}

		
    }
}


