package com.sjriley.zappit.services;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import com.sjriley.zappit.PreferencesActivity;
import com.sjriley.zappit.models.CodeCheckModel;
import com.sjriley.zappit.utils.ConnectionUtils;
import com.sjriley.zappit.vo.CodeCheckResponse;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
public class UploadService extends IntentService
{
public final static String NAME = "uploadService";
private static final String TAG = UploadService.class.getSimpleName();
private String currentCode;
public UploadService()
{
super(NAME);
}
@Override
protected void onHandleIntent(Intent intent)
{
//loop until connected
while(!ConnectionUtils.isConnected(this.getApplicationContext())) {
try
{
synchronized (this)
{
Log.d(TAG, "STILL OFFLINE");
wait(5000);
}
} catch (InterruptedException e)
{
e.printStackTrace();
return;
}
}
uploadOfflineCodes();
}
private void uploadOfflineCodes() {
Log.d(TAG,"Uploading offline codes");
try {
FileInputStream fis = openFileInput(PreferencesActivity.OFFLINE_CODES_FILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String code = null;
int count = 0;
while((code = reader.readLine()) != null) {
Log.d(TAG, "uploading Code : " + code);
currentCode = code;
uploadCode();
count ++;
}
Log.d(TAG, "Finished uploading " + count + " codes");
fis.close();
deleteFile(PreferencesActivity.OFFLINE_CODES_FILE);
}
catch (FileNotFoundException e) {
Log.d(TAG,"No File left to upload");
}
catch (Exception e){
Log.e(TAG, "error uploading offline codes", e);
synchronized (this)
{
//if the uploading failed, wait 30 seconds and try again
try {
this.wait(30000);
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
finally {
Log.e(TAG, "uploading offline codes again", e);
uploadOfflineCodes();
}
}
}
}
private void uploadCode() {
SharedPreferences prefs = getSharedPreferences(PreferencesActivity.DEFAULT_PREFERECES, 0);
String userId = prefs.getString(PreferencesActivity.USER_ID, "");
CodeCheckModel model = new CodeCheckModel(this.getApplicationContext());
CodeCheckResponse response =model.checkCode(userId, currentCode);
Log.d(TAG,"Status for " + currentCode + " is :" + response.getStatus());
}
}