package epson.epsonconnectregistration;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.LocaleList;

import java.lang.ref.WeakReference;

public abstract class ECBaseTask extends AsyncTask<Void, Void, ECStatus> {
    static final String BASE_URI_CONFIG_SERVICE = "Epson_WS_Config";
    static final String CONTENT_TYPE_SOAP = "application/soap+xml";
    private static final String TAG = "ECBaseTask";
    WeakReference<Activity> activityWeakReference = null;
    Uri rootUri = null;

    public void setContext(Activity activity) {
        activityWeakReference = new WeakReference<>(activity);
    }

    public void setRootUri(Uri uri) {
        rootUri = uri;
    }

    private Context checkParam() {
        Context context = (Context) activityWeakReference.get();
        if (context == null || rootUri == null) {
            return null;
        }
        return context;
    }

    private Uri getEndpoint() {
        return Uri.withAppendedPath(this.rootUri, BASE_URI_CONFIG_SERVICE);
    }

    private void openWebPage(Activity activity, Uri uri) {
        EPLog.d(TAG, "Open WebConfig uri = " + uri.toString());
        activity.startActivity(new Intent("android.intent.action.VIEW", uri));
    }

    private String getLang(Context context) {
        String str = "en-US";
        Configuration configuration = context.getResources().getConfiguration();
        if (configuration != null) {
            if (Build.VERSION.SDK_INT >= 24) {
                LocaleList locales = configuration.getLocales();
                if (locales.size() > 0) {
                    str = locales.get(0).toLanguageTag();
                }
            } else if (Build.VERSION.SDK_INT >= 21) {
                str = configuration.locale.toLanguageTag();
            } else {
                str = String.format("%s-%s", new Object[]{configuration.locale.getLanguage(), configuration.locale.getCountry()});
            }
        }
        if (!(str == null || str.length() == 5)) {
            String[] split = str.split("-");
            if (split.length > 2) {
                str = split[0] + "-" + split[2];
            }
            if (str.length() != 5) {
                str = String.format("%s-%s", new Object[]{configuration.locale.getLanguage(), configuration.locale.getCountry()});
            }
        }
        if (str == null || str.length() != 5) {
            str = "en-US";
        }
        EPLog.d(TAG, "getLang: " + str);
        return str;
    }
}
