package com.beloko.chochexen;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.beloko.idtech.AppSettings;
import com.beloko.idtech.GD;
import com.beloko.idtech.License;
import com.beloko.idtech.ServerAPI;
import com.beloko.idtech.Utils;
import com.beloko.idtech.chocdoom.Game;
import com.beloko.idtech.chocdoom.Setup;
import com.beloko.serial.Serial;

public class LaunchFragment extends Fragment{                           

	String LOG = "LaunchFragment";      
 
	private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwN+FZLe5kgBjlmr6FHfbsdkzrVW+SSip3Mo+8FWjSqVEuBX8Q8LGc55iQEkEM2Z2oqrGuKBNhYx+31uhiuhnsDQtn3no7iFqaV2NOrAHLqM1XbetzgN/01RxwSS7fVmlwca85HfPzEcr78iTtDZ+jXhufUNAEjylDBze8xhzU/nF0X/UKnNyA6fCmt2/LCkhvesLCNokcrVw3PS0T8P7p3AO2geD5tJa9jMxqXAF0OgyvtlGWhqsN6SBV/8iMQfaGfAHlQMHcFLV56Ddoe0E9u1PMroqKulkmu9H8rOOkKTph3LJOU9ZtV/cOmfRJxj+0CYw+moO6TsCvOiaA5d+cwIDAQAB";
	
	TextView gameArgsTextView;          
	EditText argsEditText;             
	ListView listview;  
	TextView copyWadsTextView;                                          

	String demoBaseDir;   
	String fullBaseDir;

	ArrayList<String> argsHistory = new ArrayList<String>();
  
	License licCheck; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		licCheck = new License(getActivity(),Serial.HEXEN,BASE64_PUBLIC_KEY);             
		licCheck.doCheck();
		
		demoBaseDir = AppSettings.getQuakeDemoDir();
		fullBaseDir = AppSettings.getQuakeFullDir();

		AppSettings.createDirectories(getActivity());

		Utils.loadArgs(getActivity(),argsHistory); 
	}                                          

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (GD.DEBUG) Log.d(LOG,"onHiddenChanged");
		demoBaseDir = AppSettings.getQuakeDemoDir();
		fullBaseDir = AppSettings.getQuakeFullDir();
		super.onHiddenChanged(hidden);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View mainView = inflater.inflate(R.layout.fragment_launch, null);

	
		argsEditText = (EditText)mainView.findViewById(R.id.extra_args_edittext);     
		gameArgsTextView = (TextView)mainView.findViewById(R.id.extra_args_textview);
		listview = (ListView)mainView.findViewById(R.id.listView);

		listview.setBackgroundDrawable(new BitmapDrawable(getResources(),Utils.decodeSampledBitmapFromResource(getResources(),R.drawable.hexen,587,282)));

		copyWadsTextView = (TextView)mainView.findViewById(R.id.copy_wads_textview); 
	
		Button startdemo = (Button)mainView.findViewById(R.id.start_demo);
		startdemo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (Utils.checkFiles(demoBaseDir,new String[] {"hexen.wad"}) != null)
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
					builder.setMessage("Download Hexen Shareware Data (5MB)?")
					.setCancelable(true)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) { 
							
							ServerAPI.downloadFileSecure(getActivity(),BASE64_PUBLIC_KEY,"hexen_demo.zip",demoBaseDir);
							//ServerAPI.downloadFile(getActivity(),"hexen_demo.zip",demoBaseDir);
						}
					});
					builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});                                                   
					AlertDialog alert = builder.create();
					alert.show(); 

				}     
				else 
					startGame(demoBaseDir,false); 
			}             
		});                
		Button startfull = (Button)mainView.findViewById(R.id.start_full);
		startfull.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View v) {
				String missingFiles;
				if ((missingFiles = Utils.checkFiles(fullBaseDir, new String[] {"hexen.wad"})) != null)
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
					builder.setMessage("Please copy:\n" + missingFiles + "From the full version of Hexen in to:\n" + fullBaseDir)
					.setCancelable(true)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {

						}
					});

					AlertDialog alert = builder.create();
					alert.show();
				}
				else
				{
					startGame(fullBaseDir,false);  
				}
				            
			}
		});     

		Button startmp = (Button)mainView.findViewById(R.id.start_mp);
		startmp.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View v) {
				String missingFiles;
				if ((missingFiles = Utils.checkFiles(fullBaseDir, new String[] {"hexen.wad"})) != null)
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
					builder.setMessage("Please copy:\n" + missingFiles + "From the full version of Hexen in to:\n" + fullBaseDir)
					.setCancelable(true)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {

						}
					});

					AlertDialog alert = builder.create();
					alert.show();
				}
				else
				{
					startSetup(fullBaseDir);  
				}           
			}
		});     

		
		ImageView history = (ImageView)mainView.findViewById(R.id.args_history_imageview);
		history.setOnClickListener(new View.OnClickListener() {
			//@Override
			public void onClick(View v) {  

				String[] servers = new String[ argsHistory.size()];
				for (int n=0;n<argsHistory.size();n++) servers[n] = argsHistory.get(n);

				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setTitle("Extra Args History");
				builder.setItems(servers, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						argsEditText.setText(argsHistory.get(which));
					}
				});
				builder.show();
			}        
		});

	
		//selectGame(0);
		return mainView;
	}


	
	void startGame(final String base,boolean ignoreMusic)
	{
		
		if (!licCheck.isLicensed(AppSettings.getGameDir() + "/lic.txt"))
		{
			licCheck.showBadLicense(getActivity());
			return;
		}
		
		File timiditycfg = new File(AppSettings.getBaseDir() + "/eawpats/timidity.cfg"  );
		File doomtimiditycfg = new File(AppSettings.getGameDir() + "/timidity.cfg"  );

		if (!ignoreMusic &&! timiditycfg.exists())
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage("Download Music Sound Fonts(31MB)?")
			.setCancelable(true)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					ServerAPI.downloadFileSecure(getActivity(),BASE64_PUBLIC_KEY,"eawpats.zip",AppSettings.getBaseDir());
					//ServerAPI.downloadFile(getActivity(),"eawpats.zip",AppSettings.getBaseDir());
					return;    
				}
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					startGame(base, true);
					dialog.cancel();
				}
			});                                                   
			AlertDialog alert = builder.create();
			alert.show();
			return;   
		}
    
		if (timiditycfg.exists() && !doomtimiditycfg.exists())
		{
			Log.d(LOG,"Copying timidity file");
			try {
				Utils.copyFile(new FileInputStream(timiditycfg),new FileOutputStream(doomtimiditycfg));
			} catch (FileNotFoundException e) {
				Toast.makeText(getActivity(),"Error copying timidity.cfg " + e.toString(), Toast.LENGTH_LONG).show();
			} catch (IOException e) {
				Toast.makeText(getActivity(),"Error copying timidity.cfg " + e.toString(), Toast.LENGTH_LONG).show();
			}
		}  

		
		String extraArgs = argsEditText.getText().toString().trim();

		if (extraArgs.length() > 0)
		{
			Iterator<String> it = argsHistory.iterator();
			while (it.hasNext()) { 
				String s = it.next();
				if (s.contentEquals(extraArgs))
					it.remove();
			}

			while (argsHistory.size()>50)  
				argsHistory.remove(argsHistory.size()-1);

			argsHistory.add(0, extraArgs);
			Utils.saveArgs(getActivity(),argsHistory);  
		} 

	
		String args =  gameArgsTextView.getText().toString() + " " + argsEditText.getText().toString();

		Intent intent = new Intent(getActivity(), Game.class);
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);

		intent.putExtra("game_path",base);    
		intent.putExtra("game",AppSettings.game.toString());    
		
		intent.putExtra("args","-iwad hexen.wad ");                                                
		startActivity(intent); 
	}                  

	void startSetup(final String base)
	{
		if (!licCheck.isLicensed(AppSettings.getGameDir() + "/lic.txt"))
		{
			licCheck.showBadLicense(getActivity());
			return;
		}
		
		Intent intent = new Intent(getActivity(), Setup.class);
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);

		intent.putExtra("game_path",base);    
		intent.putExtra("game",AppSettings.game.toString());    
		
		intent.putExtra("args"," ");                                                
		startActivity(intent);
	}                  


	
}
