package com.example.waoperations;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

/*import com.example.fmp.R;
import com.example.fmp.R.id;
import com.example.fmp.R.layout;
import com.example.fmp.R.string;*/

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class FirstSettingsMod extends Activity{
	  private Settings SettingsHelper;
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   
	  public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		  FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		  //Typeface fontbold = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-extrabold.ttf");
			
	    
		setContentView(R.layout.licensescreenwa);
		Intent intent = getIntent();
		SettingsHelper = new Settings(this); 
		
		ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    actionBar.setSubtitle("Registro de Licencia " );
	    actionBar.setTitle("WA Ops");
	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	    actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
	    actionBar.setDisplayShowTitleEnabled(true);
	    actionBar.setDisplayHomeAsUpEnabled(false);
	    actionBar.show(); 

     
}
	public void onBack(View view) {
	
	}
	
	public static String remover_acentos(String input) {
	    // Cadena de caracteres original a sustituir.
	    String original = "áàäéèëíìïóòöúùuñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑçÇ";
	    // Cadena de caracteres ASCII que reemplazarán los originales.
	    String ascii = "aaaeeeiiiooouuunAAAEEEIIIOOOUUUNcC";
	    String output = input;
	    for (int i=0; i<original.length(); i++) {
	        // Reemplazamos los caracteres especiales.
	        output = output.replace(original.charAt(i), ascii.charAt(i));
	    }//for i
	    return output;
	}//remove1
	
	public void onSave(View view) {


		EditText UsuarioWA = (EditText)findViewById(R.id.userwa);
		String usuario= remover_acentos(UsuarioWA.getText().toString());
	
		EditText CompanyWA = (EditText)findViewById(R.id.companywa);
		String company= CompanyWA.getText().toString();
		
		EditText LicenseWA = (EditText)findViewById(R.id.licensewa);
		String license= LicenseWA.getText().toString();
		
		Boolean autorizado=false;
		
		if(this.hasContent(usuario)==true&&this.hasContent(company)==true&&this.hasContent(license)==true){
		
		 	String v1 = "'"+usuario+"'";
			String v2 = "'"+company+"'";
			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
			String v3 = "'"+license+"'"; 
			String fecha=sdfc.format(new Date());
			String v4 = "'"+fecha+"'"; 

			try{
			 	 String result = null;
			 	InputStream is = null;
	
			 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			 	
			 	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
			 	
			  	nameValuePairs.add(new BasicNameValuePair("user",v1));
			 	nameValuePairs.add(new BasicNameValuePair("company",v2));
			 	nameValuePairs.add(new BasicNameValuePair("license",v3));
				nameValuePairs.add(new BasicNameValuePair("date",v4));

					   StrictMode.setThreadPolicy(policy); 
			        	//http post
			        	try{
			        	        HttpClient httpclient = new DefaultHttpClient();
			        	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/RegisterLicenseWA.php");
			        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			        	        HttpResponse response = httpclient.execute(httppost); 
			        	        HttpEntity entity = response.getEntity();
			        	        is = entity.getContent();

			        	        Log.e("log_tag", "connection success ");
			        	      //  Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
			        	   }
			      
			        	catch(Exception e)
			        	{
			        	        Log.e("log_tag", "Error in http connection "+e.toString());
			        	        Toast.makeText(getApplicationContext(), getString(R.string.connectionfail), Toast.LENGTH_SHORT).show();

			        	}
			        	//convert response to string
			        	try{
			        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			        	        StringBuilder sb = new StringBuilder();
			        	        String line = null;
			        	        while ((line = reader.readLine()) != null) 
			        	        {
			        	                sb.append(line + "\n");
			        	        }
			        	        is.close();

			        	        result=sb.toString();
			        	}
			        	catch(Exception e)
			        	{
			        	       Log.e("log_tag", "Error converting result "+e.toString());
			           	}
			        	try{
			        	            	JSONObject json_data = new JSONObject(result);
			        	                CharSequence w= (CharSequence) json_data.get("re");
			        	                if(w.equals("Ingreso autorizado")){autorizado=true;}
			        	  			    Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
							  	        toasta.setGravity(Gravity.CENTER,0,0);
							  	       // toasta.show();	
			        	     }
			        	catch(JSONException e)
			        	   {
			        	        Log.e("log_tag", "Error parsing data "+e.toString());
			        	        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
			        	    }}catch(Exception e){}
			
			if(autorizado){
			SettingsHelper.deleteSettings();
			SettingsHelper.saveSettings(usuario,company,license,fecha);
			Intent i = new Intent(FirstSettingsMod.this, MainActivityWA.class);
            startActivity(i);
			finish();	
			}else{
				
				 Toast.makeText(getApplicationContext(), "Licencia inválida.", Toast.LENGTH_LONG).show();	
						
				
			}}
			
			
		else{		
			 Toast.makeText(getApplicationContext(), getString(R.string.fillup), Toast.LENGTH_LONG).show();	
		}

	}

	private boolean hasContent(String datos) {
	       return (datos.trim().length() > 0);
	}
}
