package com.webileapps.excalibur;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class ExcaliburService extends Service {
    private static final String TAG = "ExcaliburService";
    private ExcaliburFragment excaliburFragment;
    private IBinder binder = new ExcaliburService.ExcaliburBinder();

    public ExcaliburService() {
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ExcaliburService", "onStartCommand");
        if (!this.excaliburFragment.isClientAndUserInitialized()) {
            Log.d("ExcaliburService", "Starting Fragment");
            SharedPreferences preferences = this.getSharedPreferences("com.webileapps.excalibur", 0);
            String clientId = preferences.getString("CLIENT_ID", (String) null);
            String userId = preferences.getString("USER_ID", (String) null);
            String username = preferences.getString("USER_NAME",null);
            String fcmToken = preferences.getString("FCM_TOKEN", (String) null);
            boolean isStaging = preferences.getBoolean("IS_STAGING", false);
            String fields = preferences.getString("CUSTOM_FIELDS", (String) null);

//            if (clientId == null) {
//                throw new UnsupportedOperationException("You need to have client_id");
//            }
//
//            if (userId == null) {
//                throw new UnsupportedOperationException("You need to have user_id");
//            }

            if (clientId != null && userId != null && username!=null) {
                if (!this.getFragment().isClientAndUserSame(clientId, userId)) {
                    this.getFragment().loadChat(clientId, userId,username, fcmToken, fields, isStaging);
                } else {
                    Log.d("ExcaliburService", "Client and User ID is same.");
                }
            }
        }

        return START_REDELIVER_INTENT;
    }

    public ExcaliburFragment getFragment() {
        return this.excaliburFragment;
    }

    public void onCreate() {
        super.onCreate();
        Log.d("ExcaliburService", "onCreate");
        this.excaliburFragment = ExcaliburFragment.newInstance(this);
    }

    public void onDestroy() {
        super.onDestroy();
        this.getFragment().wipeData();
        this.excaliburFragment = null;
        Log.d("ExcaliburService", "onDestroy");
    }

    public IBinder onBind(Intent intent) {
        return this.binder;
    }

    class ExcaliburBinder extends Binder {
        ExcaliburBinder() {
        }

        ExcaliburService getService() {
            return ExcaliburService.this;
        }
    }
}
