package com.tapjoy.easyapp;

import static com.tapjoy.easyapp.MainFragment.PREFERENCES;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class ConfigurationFragment extends Fragment {

    public static String AUTO_CONNECT_KEY = "autoConnectKey";
    public static String PREF_SDK_LIST_KEY = "sdkKeyList";
    public static String PREF_SDK_CURRENT_KEY = "sdkCurrentKey";
    public static String DEFAULT_SDK_KEY = "u6SfEbh_TA-WMiGqgQ3W8QECyiQIURFEeKm0zbOggubusy-o5ZfXp33sTXaD";

    private EditText sdkKeyInput;
    private TextView outputText;
    private Button addSdkButton;
    private CheckBox autoConnectCheckbox;
    private LinearLayout historyLayout;
    private LinearLayout configLayout;
    private SharedPreferences preferences;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.configuration, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setupUI(view);
    }

    private void setupUI(View currentView) {
        preferences = requireActivity().getApplicationContext().getSharedPreferences(PREFERENCES, 0);

        //get the UI from the xml.
        sdkKeyInput = currentView.findViewById(R.id.inputSdkKey);
        configLayout = currentView.findViewById(R.id.configLayout);
        addSdkButton = currentView.findViewById(R.id.dropDownButton);
        autoConnectCheckbox = currentView.findViewById(R.id.autoConnectCheckbox);
        historyLayout = currentView.findViewById(R.id.historyLayout);
        outputText = currentView.findViewById(R.id.textViewOutput);

        //get latest saved key
        sdkKeyInput.setText(getCurrentSdkKey());
        autoConnectCheckbox.setChecked(preferences.getBoolean(AUTO_CONNECT_KEY, true));
        autoConnectCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String message;
                if (isChecked){
                    message = getString(R.string.hint_auto_connect);
                } else {
                    message = getString(R.string.hint_manual_connect);
                }
                outputText.setText(message);
                preferences.edit().putBoolean(AUTO_CONNECT_KEY, isChecked).apply();
            }
        });

        final List<String> sdks = getListOfSdkKeysFromCache();
        initSdkList(sdks);

        sdkKeyInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    historyLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        sdkKeyInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sdkKeyInput.setError(null);
                historyLayout.setVisibility(View.VISIBLE);
            }
        });

        configLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyLayout.setVisibility(View.GONE);
            }
        });

        addSdkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sdk = sdkKeyInput.getText().toString();
                if (sdk.length() < 50){
                    sdkKeyInput.setError(getString(R.string.hint_characters));
                    return;
                }
                addNewSdkKeyToCache(sdk);
                setCurrentSdkKey(sdk);
                final List<String> sdks = getListOfSdkKeysFromCache();
                initSdkList(sdks);
                historyLayout.setVisibility(View.VISIBLE);
                outputText.setText(R.string.hint_reset_app);
            }
        });
    }

    private void initSdkList(final List<String> sdks) {
        historyLayout.removeAllViews();
        int space = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5,  getResources().getDisplayMetrics());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < sdks.size(); i++) {
            TextView textView = new TextView(requireActivity());
            textView.setText(sdks.get(i));
            textView.setTextSize(16f);
            textView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
            textView.setMaxLines(1);
            final int index = i;
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    outputText.setText(R.string.hint_reset_app);
                    String sdk = sdks.get(index);
                    sdkKeyInput.setText(sdk);
                    setCurrentSdkKey(sdk);
                    historyLayout.setVisibility(View.GONE);
                }
            });
            textView.setTextColor(ContextCompat.getColor(requireActivity(), R.color.buttonTextColor));
            params.setMargins(space, space, space, space);
            textView.setLayoutParams(params);
            historyLayout.addView(textView);
        }
    }

    //Get current SDK key from cache
    private String getCurrentSdkKey(){
        return preferences.getString(PREF_SDK_CURRENT_KEY, DEFAULT_SDK_KEY);
    }

    //Save latest SDK key to cache
    private void setCurrentSdkKey(String sdkKey){
        preferences.edit().putString(PREF_SDK_CURRENT_KEY, sdkKey).apply();
    }

    //Add SDK key to prefs
    private void addNewSdkKeyToCache(String s) {
        ArrayList<String> currentList = getListOfSdkKeysFromCache();
        currentList.remove(s);
        currentList.add(0, s);
        JSONArray jsArray = new JSONArray(currentList);
        preferences.edit().putString(PREF_SDK_CURRENT_KEY, s).apply();
        preferences.edit().putString(PREF_SDK_LIST_KEY, jsArray.toString()).apply();
    }

    //Get latest SDK key from prefs
    private ArrayList<String> getListOfSdkKeysFromCache() {
        ArrayList<String> currentList = new ArrayList<String>();
        JSONArray jArray = null;
        try {
            jArray = new JSONArray(preferences.getString(PREF_SDK_LIST_KEY, "[]"));
            for (int i = 0; i < jArray.length(); i++) {
                currentList.add(jArray.getString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //If nothing save in cache add the default sdk key
        if (currentList.isEmpty()){
            ArrayList<String> arrayList = new ArrayList<>();
            arrayList.add(DEFAULT_SDK_KEY);
            return arrayList;
        } else {
            return currentList;
        }
    }

}
