package com.mobify.astro;

import android.support.annotation.NonNull;
import android.webkit.CookieManager;

import com.mobify.astro.messaging.EventRegistrar;
import com.mobify.astro.messaging.MessageSender;
import com.mobify.astro.messaging.RpcMessageListener;
import com.mobify.astro.messaging.annotations.RpcMethod;

/**
 * Created by stevenshin on 3/14/17.
 *
 * This plugin uses single android.webkit.CookieManager to set a cookie for all instances of Webviews
 * within the app given an URL, Key and Value.
 * 
 */

public class CookiesStore extends RpcMessageListener {

    protected static final String ADDRESS = "AstroCookiesStore:0";
    private final static String TAG = CookiesStore.class.getName();

    final static String KEY_ERROR = "Key cannot be null or empty string.";
    final static String VALUE_ERROR = "Value cannot be null.";
    final static String URL_ERROR = "URL cannot be null";

    private CookieManager cookieManager;

    public class CookiesStoreException extends AstroException {
        public CookiesStoreException(String message) {
            super(TAG + ": " + message);
        }
    }

    public CookiesStore(@NonNull EventRegistrar eventRegistrar, @NonNull MessageSender messageSender) {
        super(eventRegistrar, messageSender);

        cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
    }

    @Override
    public String getInstanceAddress() {
        return ADDRESS;
    }

    @RpcMethod(methodName = "setCookie", parameterNames = {"url", "key", "value"})
    public void setCookie(String url, String key, String value) throws Exception{
        if (url == null || url.isEmpty()) {
            throw new CookiesStoreException(URL_ERROR);
        }

        if (key == null || key.isEmpty()) {
            throw new CookiesStoreException(KEY_ERROR);
        }

        if (value == null) {
            throw new CookiesStoreException(VALUE_ERROR);
        }

        cookieManager.setCookie(url, key + "=" + value);
    }

}
