package com.example.dolitbt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import cn.dolit.DLBT.DLBT_DOWNLOAD_STATE;
import cn.dolit.DLBT.DLBT_FILE_ALLOCATE_TYPE;
import cn.dolit.DLBT.DOWNLOADER_INFO;
import cn.dolit.utils.common.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.app.Activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnLongClickListener;
import android.content.DialogInterface.OnClickListener;

@SuppressLint({ "SdCardPath", "HandlerLeak", "ShowToast" })
public class MainActivity extends Activity {

	protected static final String TAG = "DolitBTDemo/";	
	
	private EditText m_torrentPathEt;
	private Button m_startBtn;
	private Button m_stopBtn;
	private TextView m_resultTv = null;	
	private int m_downloadHandle;
	
	Handler mHandler = new Handler(){

		public void handleMessage(Message msg) {
			switch (msg.what) {    
			case 1: 
				ShowDownloadInfo();
				break;    
			}    
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onDestroy()
	{
		StopDownload();
	}

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		m_downloadHandle = 0;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads().detectDiskWrites().detectNetwork() // 这里可以替换为detectAll()
																// 就包括了磁盘读写和网络I/O
		.penaltyLog() // 打印logcat，当然也可以定位到dropbox，通过文件保存相应的log
		.build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		.detectLeakedSqlLiteObjects() // 探测SQLite数据库操作
		.penaltyLog() // 打印logcat
		.penaltyDeath().build());
		m_torrentPathEt = ((EditText)findViewById(R.id.torrent_path));
	    m_resultTv = ((TextView)findViewById(R.id.result_tv));
	    m_resultTv.setMovementMethod(ScrollingMovementMethod.getInstance());
	    m_startBtn = (Button)findViewById(R.id.start_btn);
	    m_stopBtn = (Button)findViewById(R.id.stop_btn);

	    //m_torrentPathEt.setText("/mnt/sdcard/1.torrent");
	    this.m_startBtn.setOnClickListener(new View.OnClickListener()
	    {
		      public void onClick(View paramAnonymousView)
		      {
		    	  m_resultTv.setText("");
		    	  String str = m_torrentPathEt.getText().toString();
		    	  if ((str != null) && (str.length() > 0)) {
		    		  StartDownload(str);
		    	  }
		    	  else
		    	  {
		    	        try {
	    	            	InputStream is = getResources().getAssets().open("test.torrent");
	    	                FileOutputStream fos = new FileOutputStream(new File("/mnt/sdcard/test.torrent"));
	    	                byte[] buffer = new byte[1024];
	    	                while (true) {
	    	                    int len = is.read(buffer);
	    	                    if (len == -1) {
	    	                        break;
	    	                    }
	    	                    fos.write(buffer, 0, len);
	    	                }
	    	                is.close();
	    	                fos.close();
		    	        } catch (IOException e) {
		    	            // TODO Auto-generated catch block
		    	            e.printStackTrace();
		    	        }
		    	        m_torrentPathEt.setText("/mnt/sdcard/test.torrent");
			    		StartDownload("/mnt/sdcard/test.torrent");
		    	  }
		      }
	    });
	    
	    this.m_stopBtn.setOnClickListener(new View.OnClickListener()
	    {
		      public void onClick(View paramAnonymousView)
		      {
		    	  m_resultTv.setText("");
		    	  StopDownload();
		      }
	    });
	    
	    Timer timer = new Timer();
		TimerTask task = new TimerTask(){
			public void run() {
				Message message = new Message();    
				message.what = 1;    
				mHandler.sendMessage(message);  
			}
			
		};
		
		timer.schedule(task, 1000, 1000); 	    
	    
	    // 为了方便测试，增加了长按自动复制全部结果的功能
	    m_resultTv.setOnLongClickListener(new OnLongClickListener() {
	    	 
	    	@Override
	    	public boolean onLongClick(View arg0) {	    	 
	    		ShowCopyDialog();
		    	return false;
	    	}
	    });
	}


	 /**
     * 传入一个torrent的路径，开始进行下载
     */
	
	protected void StartDownload(String torrentPath)
	{    
	    /**
	     * 解析前先判断mDolitBT对象是否存在，如果没有创建一次
	     */		
		MainApplication app = (MainApplication)this.getApplication();
        if (app.mDolitBT == null) {
            app.initDolitBT();
        }

		File dir = new File("/mnt/sdcard/btCache/");
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		String outPath = "/mnt/sdcard/btCache/";
		String statusFile = "/mnt/sdcard/btCache/1.dlbt";
		
		// 如果之前的任务存在，首先关闭掉
		if (m_downloadHandle != 0)
			app.mDolitBT.DLBT_Downloader_Release(m_downloadHandle, 0);
		m_downloadHandle = 0;
		
		Log.i(TAG, "To start download");
		m_downloadHandle = app.mDolitBT.DLBT_Downloader_Initialize(torrentPath, outPath, statusFile,
			DLBT_FILE_ALLOCATE_TYPE.FILE_ALLOCATE_REVERSED, false, false, null, null, false, false);
		
		Log.i(TAG, "start finished: " + m_downloadHandle);
		
		if (m_downloadHandle == 0)
			m_resultTv.setText( "启动下载失败" );
	}
	
	protected void StopDownload()
	{   
		if (m_downloadHandle != 0)
  	  	{
			MainApplication app = (MainApplication)this.getApplication();
			if (app.mDolitBT == null)
				return;
			
			Log.i(TAG, "To Stop task: " + m_downloadHandle);
			app.mDolitBT.DLBT_Downloader_Release(m_downloadHandle, 0);
			Log.i(TAG, "stop finished: " + m_downloadHandle);
			m_downloadHandle = 0;
  	  	}
	}
	
	public void ShowDownloadInfo()
	{
		if (m_downloadHandle == 0)
			return;
		MainApplication app = (MainApplication)this.getApplication();
		if (m_resultTv == null || app.mDolitBT == null)
			return;
		
		Log.i(TAG, "to get info");
		DOWNLOADER_INFO info = app.mDolitBT.DLBT_GetDownloaderInfo(m_downloadHandle);		
		if (info == null)
			return;
	
		DLBT_DOWNLOAD_STATE state = info.state;
		String str = "";
		str += "当前状态：";
			switch (state)
			{
			case BTDS_QUEUED:
				str += ("初始化");
				break;
			case BTDS_CHECKING_FILES:
				str += ("检查文件");
				break;
			case BTDS_DOWNLOADING_TORRENT:
				str += ("获取种子");
				break;
			case BTDS_DOWNLOADING:
				str += ("下载中");
				break;
			case BTDS_PAUSED:
				str += ("暂停");
				break;
			case BTDS_FINISHED:
				str += ("下载完成");
				break;
			case BTDS_SEEDING:
				str += ("供种中");
				break;
				case BTDS_ALLOCATING:
				str += ("分配存储空间");
				break;
			case BTDS_ERROR:
				str += "遇到错误：";
				str += app.mDolitBT.DLBT_Downloader_GetLastError(m_downloadHandle);
			}

		str += "  文件大小：" + Utils.GetDisplayFileSize(info.totalFileSize);
		str += "  已经下载：" + Utils.GetDisplayFileSize(info.totalDownloadedBytes);
		str += "  当前进度：" + Utils.FloatToStr(info.currentTaskProgress) + "% ";
		long uLeft = info.totalFileSize - info.totalDownloadedBytes;
		String strLeftTime;
		long uSpeed = info.downloadSpeed;
		if (uSpeed <= 0)
			strLeftTime = "";
		else
			strLeftTime = Utils.SecondToStr((Long) (uLeft / uSpeed));

		str += "  剩余时间：" + strLeftTime;
		str += "  下载速度：" + Utils.GetDisplayFileSize(info.downloadSpeed) + "/s ";
        
		Log.i(TAG, str);
		m_resultTv.setText( str );
	}
	
	// 为了方便测试解析出来的地址是否可以下载，增加了长按自动复制全部结果的功能
	public Dialog ShowCopyDialog() {
		 
		Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
		.setNegativeButton("取消", null)
		.setItems(new String[] { "复制" }, new OnClickListener() {		 
			public void onClick(DialogInterface dialog, int which) {
			String string = m_resultTv.getText().toString();
			copy(string, getBaseContext());
			Toast.makeText(getBaseContext(), "文本已复制到粘贴板", 2000)
			.show();
		}
		}).create();
		
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		return dialog;		 
	}
		 
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public static void copy(String content, Context context) {
		// 得到剪贴板管理器
		ClipboardManager cmb = (ClipboardManager) context
		.getSystemService(Context.CLIPBOARD_SERVICE);
		cmb.setText(content.trim());
		}
    
}
