package com.beloko.quaketouch;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.beloko.quaketouch.R;

public class Utils {
	static String LOG = "Utils";


	/*
	public void downloadData(String url, String path)
	{
		new DLFileThread().execute(url,path);
	}

	private class DLFileThread extends AsyncTask<String, Integer, Long> {

		private ProgressDialog progressBar;
		String errorstring= null;

		@Override
		protected void onPreExecute() {
			progressBar = new ProgressDialog(ctx); 
			progressBar.setMessage("Downloading/Extracting files..");
			progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressBar.setCancelable(false);
			progressBar.show();
		}

		protected Long doInBackground(String... info) {

			String urlfile = info[0];
			String basePath = info[1];

			progressBar.setProgress(0);

			File outZipFile = new File(basePath,"temp.zip");
			try
			{
				BufferedInputStream in = null;
				FileOutputStream fout = null;
				URL url = new URL(urlfile);
				URLConnection con;
				con = url.openConnection();
			
				con.setConnectTimeout(4000);
				con.setReadTimeout(8000);
				InputStream ins = con.getInputStream();
				int dlSize = con.getContentLength();
				progressBar.setMax(dlSize);
				if (GD.DEBUG) Log.d(LOG,"Rott demo size = " + dlSize);

				in = new BufferedInputStream(ins);
				fout = new FileOutputStream(outZipFile);

				byte data[] = new byte[1024];
				int count;
				while ((count = in.read(data, 0, 1024)) != -1)
				{
					fout.write(data, 0, count);
					progressBar.setProgress(progressBar.getProgress() + count);
				}
				in.close();
				fout.close();
			} catch (IOException e) {
				errorstring = e.toString();
				return 1l;
			}

			InputStream in = null;
			OutputStream out = null;

			progressBar.setMax(2);
			progressBar.setProgress(0);
			try {
				ZipFile zipFile = new ZipFile(outZipFile);
				Enumeration entries = zipFile.entries();
				while(entries.hasMoreElements()) {
					ZipEntry entry = (ZipEntry)entries.nextElement();
					if(entry.isDirectory()) {
						// Assume directories are stored parents first then children.
						System.err.println("Extracting directory: " + entry.getName());
						// This is not robust, just for demonstration purposes.
						(new File(basePath, entry.getName())).mkdirs();
						continue;
					}
					if (GD.DEBUG) Log.d(LOG,"Extracting file: " + entry.getName());
					(new File(basePath, entry.getName())).getParentFile().mkdirs();
					in = zipFile.getInputStream(entry);
					out =  new FileOutputStream(new File(basePath, entry.getName()));
					copyFile(in,out);
					progressBar.setProgress(progressBar.getProgress() + 1);
				}
				//zipFile.close();
			} catch (IOException ioe) {
				if (GD.DEBUG) Log.d(LOG, "Error reading zip " + out + " - " + ioe.toString());
				errorstring = ioe.toString();
				return 1l;
			}


			outZipFile.delete();

			return 0l;
		}

		protected void onProgressUpdate(Integer... progress) {

		}

		protected void onPostExecute(Long result) {
			progressBar.dismiss();
			if (errorstring!=null)
				Toast.makeText(ctx, "Error: " + errorstring, Toast.LENGTH_LONG).show();
		}
	}
*/
	static public void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while((read = in.read(buffer)) != -1){
			out.write(buffer, 0, read);
		}
		out.close(); 
	}

	public static boolean checkFiles(String basePath, boolean demo)
	{
		File[] files = new File(basePath+ "/id1/").listFiles();
		boolean ok=true;
		String[] demo_files = {"pak0.pak"};
		String[] full_files = {"pak0.pak","pak1.pak"};

		String[] expected;

		if (demo)
			expected = demo_files;
		else
			expected = full_files;

		if (files!=null)
		{

			for (String e: expected)
			{
				boolean found=false;
				for (File f: files)
				{
					//Log.d(LOG,"check " + f.toString());
					if (f.toString().toLowerCase().endsWith(e))
						found = true;
				}
				if (!found) ok = false;
			}
		}
		else	
			ok =  false;

		return ok;
	}

	public static boolean expired()
	{
		final Calendar c = Calendar.getInstance();
		int  year = c.get(Calendar.YEAR);
		int  month = c.get(Calendar.MONTH) + 1;
		int  day = c.get(Calendar.DAY_OF_MONTH);

		if (year > 2013)
			GD.expired = true;

		if (month > 4)
			GD.expired = true;

		if (GD.expired)
			return true;


		Thread thread = new Thread()
		{
			@Override
			public void run() {
				try {
					try
					{
						BufferedInputStream in = null;
						FileOutputStream fout = null;
						URL url = new URL("http://www.beloko.com/QUAKE/text.txt");
						URLConnection con;
						con = url.openConnection();
						con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 1.2.30703)");

						con.setConnectTimeout(4000);
						con.setReadTimeout(8000);
						InputStream ins = con.getInputStream();

						in = new BufferedInputStream(ins);

						byte data[] = new byte[1024];

						in.read(data, 0, 1024) ;

						Log.d(LOG," r = " + data[0]);
						if (data[0] == '1')
						{
							Log.d(LOG,"EXPIRED");
							GD.expired = true;
						}
							
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}                               
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		};

		thread.start(); 


		return false;
	}
	
	static public void copyAssets(Context ctx,String dir) {
		AssetManager assetManager = ctx.getAssets();
		String[] files = null;
		try {
			files = assetManager.list("");
		} catch (IOException e) {
			Log.e("tag", "Failed to get asset file list.", e);
		}
		for(String filename : files) {
			if (filename.endsWith("png")){
				InputStream in = null;
				OutputStream out = null;
				Log.d("test","file = " + filename);
				try {
					in = assetManager.open(filename);
					out = new FileOutputStream(dir + "/" + filename);
					copyFile(in, out);
					in.close();
					in = null;
					out.flush();
					out.close();
					out = null;
				} catch(IOException e) {
					Log.e("tag", "Failed to copy asset file: " + filename, e);
				}       
			}
		}
	}
	
	static public String[] creatArgs(String appArgs)
	{
		return appArgs.split(" ");
	}
}
