/*
Copyright (C) 2009  Ludwig M Brinckmann <ludwigbrinckmann@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */
package com.yunnanexplorer.android.gps.openmoko;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

public class UbloxAssistChipInitializer extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

//		if (!Build.MODEL.equals("freerunner")){
//			Toast t = Toast.makeText(context, context.getString(R.string.ublox_error_not_freerunner), Toast.LENGTH_LONG);
//			t.show();
//			return;
//		}

		String action = intent.getAction();

		SharedPreferences prefs = context.getSharedPreferences(Constants.sharedPreferences, Context.MODE_PRIVATE);

		if (action.equals("com.yunnanexplorer.android.gps.openmoko.INITCHIP")){

			String username = prefs.getString("ublox_username", "");
			if (username.equals("")){
				Toast t = Toast.makeText(context, context.getString(R.string.ublox_error_no_username), Toast.LENGTH_LONG);
				t.show();
				return;
			}
			String password = prefs.getString("ublox_password", "");
			double latitude = Double.parseDouble(prefs.getString("latitude", "0.0"));
			double longitude = Double.parseDouble(prefs.getString("longitude", "0.0"));
			int accuracy = Integer.parseInt(prefs.getString("accuracy", "300000"));
			String gpsdevice = prefs.getString("gpsdevice", "/dev/sc32410_serial1");
			boolean success = initializeGPSChip(context, username, password, latitude, longitude, accuracy, gpsdevice);
			if (success){
				Toast t = Toast.makeText(context, context.getString(R.string.ublox_success), Toast.LENGTH_LONG);
				t.show();
			} else {
				Toast t = Toast.makeText(context, context.getString(R.string.ublox_general_error), Toast.LENGTH_LONG);
				t.show();
			}
		} else if (action.equals("com.yunnanexplorer.android.gps.openmoko.LOCATIONSTORAGE")){
			Bundle b = intent.getExtras();
			if (b != null){    
				SharedPreferences.Editor editor = prefs.edit();
				String lat = b.getString(Constants.extra_latitude);
				if (lat != null){
					editor.putString("latitude", lat);
				}
				String lon = b.getString(Constants.extra_longitude);
				if (lon != null){
					editor.putString("longitude", lon);
				}
				String acc = b.getString(Constants.extra_accuracy);
				if (acc != null){
					editor.putString("accuracy", acc);
				}
				editor.commit();
			}
		}
	}
	private final static int responsesize = 8192; 

	private boolean initializeGPSChip(Context context, 
			String username, String password, 
			double latitude, double longitude, 
			long accuracy, String gpsdevice){

		File f = new File(gpsdevice);
		if (!f.exists() || !f.canWrite()){
			Toast.makeText(context, context.getString(R.string.ublox_error_gpsdevice) + gpsdevice, Toast.LENGTH_LONG).show();
			return false;
		}
		try {
			Socket s = new Socket("agps.u-blox.com",46434);
			byte[] response = new byte[responsesize];
			byte[] request = new String("user=" + username + ";pwd=" + password + ";cmd=full;lat=" + latitude + ";lon=" + longitude + ";pacc=" + accuracy + ";\n").getBytes();
			s.getOutputStream().write(request);
			s.getInputStream().read(response, 0, responsesize);
			String res = new String(response, "ISO-8859-1");
			int length = 0;
			if (!res.contains("Content-Type: application/ubx")){
				if (res.contains("Content-type: text/plain")){
					Toast.makeText(context, context.getString(R.string.ublox_error_service) + res, Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(context, context.getString(R.string.ublox_error_service), Toast.LENGTH_LONG).show();
				}
				return false;
			}
			int pos = res.indexOf("Content-Length: ");
			if (-1 == pos){
				Toast.makeText(context, context.getString(R.string.ublox_error_service), Toast.LENGTH_LONG).show();				
				return false;				
			}
			int end = res.indexOf("\n", pos);
			try {
				String x = res.substring(pos + 16, end).trim();
				length = Integer.parseInt(x);
			} catch (NumberFormatException e){
				Toast.makeText(context, context.getString(R.string.ublox_error_service), Toast.LENGTH_LONG).show();
				return false;
			}
			int startOfPayload = res.indexOf("\r\n\r\n");
			if (-1 == startOfPayload){
				Toast.makeText(context, context.getString(R.string.ublox_error_service), Toast.LENGTH_LONG).show();
				return false;
			}
			startOfPayload += 4;
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(response, startOfPayload, length);
			return true;
		} catch (UnknownHostException e){
			Toast.makeText(context, context.getString(R.string.ublox_error_host), Toast.LENGTH_LONG).show();
		} catch (IOException e){
			Toast.makeText(context, context.getString(R.string.ublox_error_host), Toast.LENGTH_LONG).show();
		}
		return false;
	}
}