package com.printsdksample;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import print.Print;

public class Activity_Image_Manage  extends Activity
{
	private Context thisCon;
	private Spinner spnImageIndex=null;
	private ArrayAdapter arrImageIndex;
	private TextView txtSpace=null;
	private TextView txtCounter=null;
	private ProgressDialog dialog   = null;

	private List<byte[]> lbImageIndex;
	private String[] sArrImageIndex=null;
	private String sRemainingSpace="0";
	private String sStoreSpace="0";
	private String sImageIndex="";
	int[] iSpace=new int[1];
	private int[] rEpaces;
	//图片列表
	private int IMAGELIST_SUCCEED=1;
	private int IMAGELIST_FAILURE=2;
	//总的内存大小
	private int ALL_CAPACITY_SUCCEED=3;
	private int ALL_CAPACITY_FAILURE=4;
	//剩余内存大小
	private int REMAINING_CAPACITY_SUCCEED=5;
	private int REMAINING_CAPACITY_FAILURE=6;

	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_image_manage);
		thisCon=this.getApplicationContext();

		txtSpace=(TextView)this.findViewById(R.id.txtSpace);
		txtCounter=(TextView)this.findViewById(R.id.txtCounter);

		spnImageIndex = (Spinner) findViewById(R.id.spnImageIndex);
		spnImageIndex.setOnItemSelectedListener(new OnItemSelectedImageIndex());
		progressbar = (ProgressBar) findViewById(R.id.progressbar);

		GetNVInfomation();
	}

	private class OnItemSelectedImageIndex implements OnItemSelectedListener
	{
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3)
		{
			sImageIndex=spnImageIndex.getSelectedItem().toString();
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0)
		{
			// TODO Auto-generated method stub
		}
	}

	private void GetNVInfomation()
	{
		try
		{
			int iRtn=0;
			lbImageIndex=new ArrayList<byte[]>();
			iSpace=new int[1];
			rEpaces = new int[1];
			sStoreSpace="0";
			sRemainingSpace="0";
			progressbar.setVisibility(View.VISIBLE);
			new Thread(){
				public void run() {
					Message message = new Message();
					try
					{
						int refreshImageList = Print.RefreshImageList(lbImageIndex);
						if (refreshImageList==1) {
							message.arg2=IMAGELIST_SUCCEED;
						}else {
							message.arg2=IMAGELIST_FAILURE;
						}
					}catch(Exception e){
						message.arg2=IMAGELIST_FAILURE;
					}
					handler.sendMessage(message);
					Message message1 = new Message();
					try
					{
						int refreshImageList = Print.QueryNVStoreCapacity(iSpace);
						if (refreshImageList==1) {
							sStoreSpace=String.valueOf(iSpace[0]);
						}
						int iRtn=Print.QueryNVStoreRemainingCapacity(rEpaces);
						if (iRtn==1) {
							sRemainingSpace=String.valueOf(rEpaces[0]);
						}
						if (refreshImageList==1&&iRtn==1) {
							message1.arg2=ALL_CAPACITY_SUCCEED;
						}else {
							message1.arg2=ALL_CAPACITY_FAILURE;
						}
					}catch(Exception e){
						message1.arg2=ALL_CAPACITY_FAILURE;
					}
					handler.sendMessage(message1);
				};
			}.start();
		}
		catch (Exception e)
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Image_Manage --> GetNVInfomation ")).append(e.getMessage()).toString());
		} finally {
		}
	}

	private void imageListSucceed() {
		if(lbImageIndex.size()>0)
		{
			sArrImageIndex=new String[lbImageIndex.size()];
			for(int i=0;i<lbImageIndex.size();i++){
				sArrImageIndex[i]=new String(lbImageIndex.get(i));
			}

			arrImageIndex = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,sArrImageIndex);
			arrImageIndex.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spnImageIndex.setAdapter(arrImageIndex);
		}
		else
		{
			arrImageIndex = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,new String[]{""});
			arrImageIndex.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spnImageIndex.setAdapter(arrImageIndex);
		}
	}

	public void onClickPrint(View view)
	{
		if (!checkClick.isClickEvent()) return;
		if(spnImageIndex.getItemAtPosition(0).toString().equals(""))
		{
			Toast.makeText(thisCon,R.string.activity_image_manage_download_first, Toast.LENGTH_SHORT).show();
			return;
		}
		try
		{
			int iRtn;
			Print.PrintText("Print image(keycode:"+sImageIndex+"):\n");
			iRtn=Print.PrintNVImage(sImageIndex,0);
			if(iRtn!=11)
			{
				Toast.makeText(thisCon,R.string.activity_image_manage_print_image_error, Toast.LENGTH_SHORT).show();
			}
		}
		catch (Exception e)
		{
			Log.d("HPRTSDKSample", (new StringBuilder("Activity_Image_Manage --> onClickDeleteOne ")).append(e.getMessage()).toString());
		}
	}

	public void onClickDownload(View view)
	{
		if (!checkClick.isClickEvent()) return;

		Intent myIntent = new Intent(this, Activity_PRNFile.class);
		myIntent.putExtra("Folder", android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
		myIntent.putExtra("FileFilter", "jpg,gif,png,bmp,");
		startActivityForResult(myIntent, Print.ACTIVITY_IMAGE_FILE);
	}

	public void onClickDeleteOne(View view)
	{
		if (!checkClick.isClickEvent()) return;
		if(spnImageIndex.getItemAtPosition(0).toString().equals(""))
			return;

		new AlertDialog.Builder(this)
				.setIcon(R.drawable.logo2)
				.setMessage(R.string.activity_image_manage_delete_one)
				.setTitle(R.string.activity_global_warning)
				.setPositiveButton(R.string.activity_global_yes,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int which)
							{
								int iRtn;
								try
								{
									iRtn=Print.DeleteSpecifiedNVImage(sImageIndex);
									if(iRtn>0)
									{
										Thread.sleep(200);
										GetNVInfomation();
									}
								}
								catch (Exception e)
								{
									Log.d("HPRTSDKSample", (new StringBuilder("Activity_Image_Manage --> onClickDeleteOne ")).append(e.getMessage()).toString());
								}

							}
						}
				)
				.setNegativeButton(R.string.activity_global_no,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,int which)
							{
								// TODO Auto-generated method stub

							}
						}
				) .show();
	}

	public void onClickDeleteAll(View view)
	{
		if (!checkClick.isClickEvent()) return;
		if(spnImageIndex.getItemAtPosition(0).toString().equals(""))
			return;

		new AlertDialog.Builder(this)
				.setIcon(R.drawable.logo2)
				.setMessage(R.string.activity_image_manage_delete_one)
				.setTitle(R.string.activity_global_warning)
				.setPositiveButton(R.string.activity_global_yes,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int which)
							{
								int iRtn;
								try
								{
									iRtn=Print.DeleteAllNVImage();
									if(iRtn>0)
									{
										Thread.sleep(3000);
										GetNVInfomation();
									}
								}
								catch (Exception e)
								{
									Log.d("HPRTSDKSample", (new StringBuilder("Activity_Image_Manage --> onClickDeleteOne ")).append(e.getMessage()).toString());
								}
							}
						}
				)
				.setNegativeButton(R.string.activity_global_no,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,int which)
							{
								// TODO Auto-generated method stub

							}
						}
				) .show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		try
		{
			switch(resultCode)
			{
				case Print.ACTIVITY_IMAGE_FILE:
					final String strImageFile=data.getExtras().getString("FilePath");
					final File file = new File(strImageFile);
					if(file.exists())
					{
						InputStream isFile = null;
						int FileByteLen = 0;
						int PacketCount=0;

						dialog = new ProgressDialog(Activity_Image_Manage.this);
						dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						dialog.setTitle(R.string.activity_image_manage_btndownload);
						dialog.setMessage(getApplication().getString(R.string.activity_image_manage_downloading_NV_image));
						dialog.setMax(PacketCount);
						dialog.setIndeterminate(false);
						dialog.setCancelable(false);
						dialog.show();
						new Thread()
						{
							public void run()
							{
								try
								{
									Looper.prepare();
									try
									{
										if(DownloadNVImage(strImageFile))
										{
											dialog.cancel();
											Toast.makeText(thisCon, R.string.activity_image_manage_define_NV_image_success, Toast.LENGTH_LONG).show();
											runOnUiThread(new Runnable() {
												public void run() {
													GetNVInfomation();
												}
											});
										}
										else
											Toast.makeText(thisCon, R.string.activity_image_manage_define_NV_image_error, Toast.LENGTH_LONG).show();
									}
									catch(Exception e)
									{
										e.getStackTrace();
									}
									dialog.cancel();
									Looper.loop();
								}
								catch (Exception e)
								{
									dialog.cancel();
								}
							}
						}.start();
					}
					return;
			}
		}
		catch(Exception e)
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Image_Manage --> onActivityResult ")).append(e.getMessage()).toString());
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean DownloadNVImage(String ImageFile)
	{
		try
		{
			int iRtn;
			String[] sArrFile=new String[1];
			sArrFile[0]=ImageFile;
			iRtn=Print.DefineNVImage(sArrFile,handler);
			return iRtn==1;
		}
		catch(Exception e)
		{
			Log.e("HPRTSDKSample", (new StringBuilder("Activity_Image_Manage --> DownloadNVImage ")).append(e.getMessage()).toString());
		}
		return false;
	}

	private Handler handler=new Handler()
	{
		public void handleMessage(Message msg)
		{
			progressbar.setVisibility(View.GONE);
			if(msg.what>0)
				dialog.setMax(msg.what);
			if(msg.arg1>0)
				dialog.setProgress(msg.arg1);
			if (msg.arg2==IMAGELIST_SUCCEED) {
				imageListSucceed();
				txtCounter.setText(getString(R.string.activity_image_manage_txtCounter).replace("N", String.valueOf(lbImageIndex.size())));
			}
			if (msg.arg2==IMAGELIST_FAILURE) {
				Toast.makeText(thisCon, getString(R.string.activity_image_manage_no_support), Toast.LENGTH_SHORT).show();
			}
			if (msg.arg2==ALL_CAPACITY_SUCCEED) {
				txtSpace.setText(getString(R.string.activity_image_manage_txtSpace).replace("N", sStoreSpace).replace("M", sRemainingSpace));
			}
			if (msg.arg2==ALL_CAPACITY_FAILURE){
				Toast.makeText(thisCon, getString(R.string.activity_image_manage_no_support), Toast.LENGTH_SHORT).show();
			}
		}
	};
	private ProgressBar progressbar;

}
