package kz.arta.synergy.workflow.mobile.android;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import kz.arta.synergy.workflow.mobile.android.authorization.SynergyAccount;
import kz.arta.synergy.workflow.mobile.android.common.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.requests.Positions;
import kz.arta.synergy.workflow.mobile.android.common.utils.DateUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;

/**
 * Created by neox on 25.12.14.
 * Сервис для получения и отправки данных о местоположении пользователя
 */
public class GeolocationService extends Service {

    private Person person;
    final LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(final Location location) {
            if (location != null && Utils.isOnline(getApplicationContext(), null)) {
                Map<String, String> data = new HashMap<String, String>();
                data.put("user", person.getFirstname() + " " + person.getLastname());
                data.put("userID", person.getUuid());
                data.put("locDate", DateUtils.getDateFromMilliseconds(String.valueOf(System.currentTimeMillis())));
                data.put("lat", String.valueOf(location.getLatitude()));
                data.put("lon", String.valueOf(location.getLongitude()));
                Toast.makeText(getApplicationContext(), new Gson().toJson(data), Toast.LENGTH_LONG).show();
                new Positions(person, new Gson().toJson(data)).execute();
            } else {
                Toast.makeText(getApplicationContext(), "location = null", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LocationManager locManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        SharedPreferences mSettings = getApplicationContext().getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);
        AccountManager accountManager = AccountManager.get(getApplicationContext());
        Account[] accounts = accountManager.getAccounts();
        for (Account account : accounts) {
            if (account.type.equals(SynergyAccount.TYPE)) {
                person = new Person();
                person.setPassword(accountManager.getPassword(account));
                person.setLogin(accountManager.getUserData(account, SynergyAccount.LOGIN));
                person.setHost(accountManager.getUserData(account, SynergyAccount.HOST));
                person.setShortHost(accountManager.getUserData(account, SynergyAccount.SHORT_HOST));
                person.setUuid(accountManager.getUserData(account, SynergyAccount.USER_ID));
                person.setFirstname(accountManager.getUserData(account, SynergyAccount.FIRSTNAME));
                person.setLastname(accountManager.getUserData(account, SynergyAccount.LASTNAME));
                if (locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            Long.parseLong(mSettings.getString(SettingsConst.PERIOD_MILLISECONDS_POSITION, "")), 0, mLocationListener);
                } else if (locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                    locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            Long.parseLong(mSettings.getString(SettingsConst.PERIOD_MILLISECONDS_POSITION, "")), 0, mLocationListener);
                }
                break;
            }
        }
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
