package com.rockear.lrc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

/**
 * @author howard
 * 
 */
public class LrcUtils {

	/**
	 * @author howard get the lrc url using title and artist name
	 * 
	 */
	public class GetJsonLrc extends AsyncTask<String, Integer, String> {
		String title = "";
		String artist = "";
		String url = "";

		/**
		 * @param name
		 * @param artist
		 */
		public GetJsonLrc(String name, String artist) {
			super();
			title = name;
			this.artist = artist;
			getProperUrl();
		}

		private void getProperUrl() {
			if (artist != null && !artist.equals("")) {
				url = "http://geci.me/api/lyric/" + title + "/" + artist;
			} else {
				url = "http://geci.me/api/lyric/" + title;
			}
			Log.e("howard", "task lrc started>>>>>>>>" + url);
		}

		@Override
		protected void onPreExecute() {
			LrcConstant.DOWNLOADING = false;
			LrcConstant.SEARCHING = true;
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected String doInBackground(String... unneeded) {

			String lrcurl = "";
			try {
				HttpClient httpClient = new DefaultHttpClient();
				Log.e("howard", "task lrc started>>>>>>>>" + url);
				HttpPost httpPost = new HttpPost(url);
				HttpResponse httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					String jsonString = EntityUtils.toString(
							httpResponse.getEntity(), "utf-8");
					JSONObject root = new JSONObject(jsonString);
					JSONArray items = root.getJSONArray("result");
					for (int i = 0; i < 1; i++) {
						lrcurl = items.getJSONObject(i).getString("lrc");
					}
				}
			} catch (Exception e) {
				Log.e("howard", e.getMessage());
				lrcurl = "-1";
			}
			Log.e("howard", "task lrc started>>>>>>>>" + lrcurl);
			return lrcurl;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result.length() > 5) {
				DownLrc task = new DownLrc(result, title);
				task.execute();
			} else {

			}
		}
	}

	/**
	 * @author howard download the lrc by lrc url
	 * 
	 */
	public class DownLrc extends AsyncTask<Void, Integer, String> {
		public String mUrl = "";
		String title = "";

		private String fileDir = Environment.getExternalStorageDirectory()
				.toString() + "/.rockEar/lrc";

		public DownLrc(String url, String name) {
			mUrl = url;
			title = name;
		}

		@Override
		protected void onPreExecute() {
			LrcConstant.DOWNLOADING = true;
			LrcConstant.SEARCHING = false;
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			String filePath = null;
			InputStream is = null;
			FileOutputStream fos = null;
			HttpURLConnection conn = null;
			RandomAccessFile raf = null;
			try {
				long total = HttpUtils.getNetFileSize(mUrl);
				URL url = new URL(mUrl);
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5 * 1000);
				conn.setReadTimeout(1000 * 10);
				conn.setRequestMethod("GET");
				File upgradeDir = new File(fileDir);
				if (!upgradeDir.exists()) {
					upgradeDir.mkdirs();
				}
				File upgrade = new File(upgradeDir, title + ".lrc");
				long fileLength = upgrade.length();
				if (fileLength == total) {
					filePath = upgrade.getAbsolutePath();
					return filePath;
				}
				conn.setRequestProperty("RANGE", "bytes=" + fileLength + "-");
				conn.connect();
				is = conn.getInputStream();
				int preciousProgress = 0;
				long size = fileLength;
				int count = 0;
				raf = new RandomAccessFile(upgrade, "rws");
				byte[] temp = new byte[1024 * 60];
				raf.seek(fileLength);
				count = is.read(temp, 0, temp.length);
				while (count > 0) {
					raf.write(temp, 0, count);
					size += count;
					int progress = (int) (size * 100 / total);
					if (progress - preciousProgress > 0) {
						preciousProgress = progress;
					}
					count = is.read(temp, 0, temp.length);
				}
				raf.close();
				filePath = upgrade.getAbsolutePath();
			} catch (MalformedURLException e) {
				return null;
			} catch (IOException e) {
				return null;
			} finally {
				HttpUtils.closeInputStream(is);
				HttpUtils.closeOutputStream(fos);
				if (raf != null) {
					try {
						raf.close();
					} catch (IOException e) {
					}
				}
			}
			return filePath;
		}

		@Override
		protected void onPostExecute(String result) {
			LrcConstant.DOWNLOADING = false;
			LrcConstant.SEARCHING = false;
			if (LrcReader.read(result + title + ".lrc")) {
				Log.e("howard", "task lrc started>>>>>>>>" + result);
			}
			super.onPostExecute(result);
		}
	}

}
