/*
 * Copyright (c) 2011-2019, Zingaya, Inc. All rights reserved.
 */

package com.reactsocks.vpnforegroundservice;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;

import android.util.Log;

import android.net.VpnService;

import android.app.Activity;

import android.support.v4.content.LocalBroadcastManager;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;


import static com.reactsocks.vpnforegroundservice.Constants.ERROR_INVALID_CONFIG;
import static com.reactsocks.vpnforegroundservice.Constants.ERROR_SERVICE_ERROR;
import static com.reactsocks.vpnforegroundservice.Constants.NOTIFICATION_CONFIG;
import static com.reactsocks.vpnforegroundservice.Constants.E_ACTIVITY_DOES_NOT_EXIST;
import static com.reactsocks.vpnforegroundservice.Constants.SERVICE_STOP;

public class VPNForegroundServiceModule extends ReactContextBaseJavaModule {

    private final ReactApplicationContext reactContext;
    private ReadableMap config;
    private Promise promise;
    private String ip,user,password;
    private int port;

    private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {

        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {

                if (resultCode == Activity.RESULT_OK) {
                    Intent newIntent = new Intent(getReactApplicationContext(), VPNForegroundService.class);
                    newIntent.setAction(Constants.ACTION_FOREGROUND_SERVICE_START);
                    newIntent.putExtra(NOTIFICATION_CONFIG, Arguments.toBundle(config));
                    newIntent.putExtra("ip",ip);
                    newIntent.putExtra("port",port);
                    newIntent.putExtra("user",user);
                    newIntent.putExtra("password",password);
                    ComponentName componentName = getReactApplicationContext().startService(newIntent);
                    if (componentName != null) {
                        promise.resolve(null);
                    } else {
                        promise.reject(ERROR_SERVICE_ERROR, "VPNForegroundService: Foreground service is not started");
                    }
                } else {
                    promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: text is required");
                    return;
                }

            }
        }
    };

    public VPNForegroundServiceModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
        reactContext.addActivityEventListener(mActivityEventListener);

    }

    @Override
    public String getName() {
        return "VPNForegroundService";
    }

    @ReactMethod
    public void createNotificationChannel(ReadableMap channelConfig, Promise promise) {
        if (channelConfig == null) {
            promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: Channel config is invalid");
            return;
        }
        NotificationHelper.getInstance(getReactApplicationContext()).createNotificationChannel(channelConfig, promise);
    }

    @ReactMethod
    public void startService(ReadableMap notificationConfig, String ip, int port, String user, String password, Promise promise) {

        this.config = notificationConfig;
        this.promise = promise;
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.password = password;

        if (notificationConfig == null) {
            promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: Notification config is invalid");
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!notificationConfig.hasKey("channelId")) {
                promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: channelId is required");
                return;
            }
        }

        if (!notificationConfig.hasKey("id")) {
            promise.reject(ERROR_INVALID_CONFIG , "VPNForegroundService: id is required");
            return;
        }

        if (!notificationConfig.hasKey("icon")) {
            promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: icon is required");
            return;
        }

        if (!notificationConfig.hasKey("title")) {
            promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: title is reqired");
            return;
        }

        if (!notificationConfig.hasKey("text")) {
            promise.reject(ERROR_INVALID_CONFIG, "VPNForegroundService: text is required");
            return;
        }

        Activity currentActivity = getCurrentActivity();

        if (currentActivity == null) {
            promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "VPNForegroundService: Activity doesn't exist");
            return;
        }

        Intent intent = VpnService.prepare(reactContext);
        if (intent != null) {
            currentActivity.startActivityForResult(intent, 0);
        } else {
            //onActivityResult(0, RESULT_OK, null);
            Intent startIntent = new Intent(reactContext, VPNForegroundService.class);
            startIntent.setAction(Constants.ACTION_FOREGROUND_SERVICE_START);
            startIntent.putExtra(NOTIFICATION_CONFIG, Arguments.toBundle(notificationConfig));
            startIntent.putExtra("ip",ip);
            startIntent.putExtra("port",port);
            startIntent.putExtra("user",user);
            startIntent.putExtra("password",password);

            ComponentName componentName = reactContext.startService(startIntent);
            if (componentName != null) {
                promise.resolve(null);
            } else {
                promise.reject(ERROR_SERVICE_ERROR, "VPNForegroundService: Foreground service is not started");
            }
        }
        //promise.resolve(null);


    }


    @ReactMethod
    public void stopService(Promise promise) {
        Log.d("VPNService","Stop service");
        /*Intent stopIntent = new Intent(reactContext, VPNForegroundService.class);
        stopIntent.setAction(Constants.ACTION_FOREGROUND_SERVICE_STOP);
        boolean stopped = reactContext.stopService(stopIntent);*/

        Intent ruleset = new Intent(SERVICE_STOP);
        reactContext.sendBroadcast(ruleset);

        //if (stopped) {
            promise.resolve(null);
        //} else {
        //    promise.reject(ERROR_SERVICE_ERROR, "VPNForegroundService: Foreground service failed to stop");
        //}
    }


}