package com.tapjoy.easyapp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.fragment.app.Fragment;

import com.tapjoy.TJPrivacyPolicy;
import com.tapjoy.TJSegment;
import com.tapjoy.TJSetUserIDListener;
import com.tapjoy.TJStatus;
import com.tapjoy.Tapjoy;

import java.util.Objects;


public class UserFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    // UI
    private Button buttonUserInfoSet;
    private Button buttonUserInfoClear;
    private Button buttonUserTagsAdd;
    private Button buttonUserTagsSub;
    private Button buttonUserTagsClear;

    private EditText editTextUserId;
    private EditText editTextUserLevel;
    private EditText editTextUserMaxLevel;
    private EditText editTextUserTag;
    private Spinner spinnerUserSegment;

    private TJPrivacyPolicy tjPrivacyPolicy;

    private Spinner spinnerGDPR;
    private Spinner spinnerUserConsent;
    private Spinner spinnerBelowConsentAge;
    private Spinner spinnerUsageStatsConsent;
    private EditText inputUSPrivacy;
    private Button buttonUSPrivacy;
    private SwitchCompat optOutAdvertisingIDSwitch;

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        tjPrivacyPolicy = Tapjoy.getPrivacyPolicy();
        setupUI(view);
    }

    /**
     * Sets user info
     */
    private void setUserInfo() {
        String inputUserId = editTextUserId.getText().toString();
        String userLevel = editTextUserLevel.getText().toString();
        String userMaxLevel = editTextUserMaxLevel.getText().toString();

        int inputUserLevel = -1;
        int inputUserMaxLevel = -1;

        if (!userLevel.isEmpty()) {
            inputUserLevel = Integer.parseInt(userLevel);
        }
        if (!userMaxLevel.isEmpty()) {
            inputUserMaxLevel = Integer.parseInt(userMaxLevel);
        }

        // Set user info
        Tapjoy.setUserID(inputUserId, new TJSetUserIDListener() {
            @Override
            public void onSetUserIDSuccess() {
                Toast.makeText(getContext(), "User ID set", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSetUserIDFailure(int code, String error) {
                Toast.makeText(getContext(), "User ID failed: " + error + " code: " + code, Toast.LENGTH_SHORT).show();
            }
        });
        Tapjoy.setUserLevel(inputUserLevel);
        Tapjoy.setMaxLevel(inputUserMaxLevel);

        // Set all user tags
        //Tapjoy.setUserTags(new HashSet<String>(userTagsValues));
    }

    /**
     * Clears all input fields
     */
    private void clearInputs() {
        // Clear edit texts
        editTextUserId.setText("");
        editTextUserLevel.setText("");
        editTextUserMaxLevel.setText("");

        Tapjoy.setUserLevel(-1);
        Tapjoy.setMaxLevel(-1);
        Tapjoy.setUserID(null, null);

        Toast.makeText(getContext(), "Inputs cleared", Toast.LENGTH_SHORT).show();
    }

    /**
     * Handles button clicks
     */
    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            final Button button = ((Button) v);
            int id = button.getId();

            if (id == R.id.buttonUserTagAdd) {
                Tapjoy.addUserTag(editTextUserTag.getText().toString());
                editTextUserTag.setText("");
            } else if (id == R.id.buttonUserTagSubtract) {
                Tapjoy.removeUserTag(editTextUserTag.getText().toString());
                editTextUserTag.setText("");
            } else if (id == R.id.buttonUserTagClear) {
                Tapjoy.clearUserTags();
                editTextUserTag.setText("");
            } else if (id == R.id.buttonUserInfoSet) {
                setUserInfo();
            } else if (id == R.id.buttonUserInfoClear) {
                clearInputs();
            }
            if (id == R.id.buttonUSPrivacy) {
                String usPrivacyValue = inputUSPrivacy.getText().toString();
                tjPrivacyPolicy.setUSPrivacy(usPrivacyValue);

                if (usPrivacyValue.isEmpty()) {
                    Toast.makeText(requireContext(), "Removed US Privacy Value.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(requireContext(), "Saved US Privacy Value.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * Changes text of privacy policy.
     */
    @Override
    public void onItemSelected(AdapterView<?> spinner, View view, int index, long rowId) {
        int id = spinner.getId();
        if (id == R.id.spinnerGDPR) {
            tjPrivacyPolicy.setSubjectToGDPR(getStatusFromIndex(index));
        } else if (id == R.id.spinnerUserConsent) {
            tjPrivacyPolicy.setUserConsent(getStatusFromIndex(index));
        } else if (id == R.id.spinnerBelowConsentAge) {
            tjPrivacyPolicy.setBelowConsentAge(getStatusFromIndex(index));
        } else if (id == R.id.spinnerUsageStatsConsent) {
            tjPrivacyPolicy.setUsageStatsConsent(getStatusFromIndex(index));
        } else if (id == R.id.spinnerUserSegment) {
            switch (index) {
                case 0:
                    Tapjoy.setUserSegment(TJSegment.NON_PAYER);
                    break;
                case 1:
                    Tapjoy.setUserSegment(TJSegment.PAYER);
                    break;
                case 2:
                    Tapjoy.setUserSegment(TJSegment.VIP);
                    break;
                default:
                    Tapjoy.setUserSegment(TJSegment.UNKNOWN);
            }
        }
    }

    private TJStatus getStatusFromIndex(int index) {
        switch (index) {
            case 0: return TJStatus.TRUE;
            case 1: return TJStatus.FALSE;
            default: return TJStatus.UNKNOWN;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }

    /**
     * Grabs references to UI elements and sets up listeners
     */
    private void setupUI(View currentView) {

        buttonUserInfoSet = currentView.findViewById(R.id.buttonUserInfoSet);
        buttonUserInfoSet.setOnClickListener(this);
        buttonUserInfoClear = currentView.findViewById(R.id.buttonUserInfoClear);
        buttonUserInfoClear.setOnClickListener(this);

        // User tags
        buttonUserTagsAdd = currentView.findViewById(R.id.buttonUserTagAdd);
        buttonUserTagsAdd.setOnClickListener(this);

        buttonUserTagsSub = currentView.findViewById(R.id.buttonUserTagSubtract);
        buttonUserTagsSub.setOnClickListener(this);

        buttonUserTagsClear = currentView.findViewById(R.id.buttonUserTagClear);
        buttonUserTagsClear.setOnClickListener(this);

        editTextUserId = currentView.findViewById(R.id.inputUserId);
        editTextUserLevel = currentView.findViewById(R.id.inputUserLevel);
        editTextUserMaxLevel = currentView.findViewById(R.id.inputUserMaxLevel);
        editTextUserTag = currentView.findViewById(R.id.inputUserTag);

        spinnerUserSegment = currentView.findViewById(R.id.spinnerUserSegment);
        spinnerUserSegment.setOnItemSelectedListener(this);

        spinnerGDPR = currentView.findViewById(R.id.spinnerGDPR);
        spinnerUserConsent = currentView.findViewById(R.id.spinnerUserConsent);
        spinnerBelowConsentAge = currentView.findViewById(R.id.spinnerBelowConsentAge);
        spinnerUsageStatsConsent = currentView.findViewById(R.id.spinnerUsageStatsConsent);
        inputUSPrivacy = currentView.findViewById(R.id.inputUSPrivacy);
        buttonUSPrivacy = currentView.findViewById(R.id.buttonUSPrivacy);
        optOutAdvertisingIDSwitch = currentView.findViewById(R.id.switchOptOutAdvertisingID);

        spinnerGDPR.setOnItemSelectedListener(this);
        spinnerUserConsent.setOnItemSelectedListener(this);
        spinnerBelowConsentAge.setOnItemSelectedListener(this);
        spinnerUsageStatsConsent.setOnItemSelectedListener(this);

        optOutAdvertisingIDSwitch.setChecked(Tapjoy.getOptOutAdvertisingID(requireContext()));

        optOutAdvertisingIDSwitch.setOnCheckedChangeListener((compoundButton, checked) -> {
            Tapjoy.optOutAdvertisingID(this.getContext(), checked);
        } );

        buttonUSPrivacy.setOnClickListener(this);

        if (tjPrivacyPolicy.getSubjectToGDPR() == TJStatus.TRUE) {
            spinnerGDPR.setSelection(0);
        } else if (tjPrivacyPolicy.getSubjectToGDPR() == TJStatus.FALSE) {
            spinnerGDPR.setSelection(1);
        } else {
            spinnerGDPR.setSelection(2);
        }

        if (tjPrivacyPolicy.getUserConsent() == TJStatus.TRUE) {
            spinnerUserConsent.setSelection(0);
        } else if (tjPrivacyPolicy.getUserConsent() == TJStatus.FALSE) {
            spinnerUserConsent.setSelection(1);
        } else {
            spinnerUserConsent.setSelection(2);
        }

        if (tjPrivacyPolicy.getBelowConsentAge() == TJStatus.TRUE) {
            spinnerBelowConsentAge.setSelection(0);
        } else if (tjPrivacyPolicy.getBelowConsentAge() == TJStatus.FALSE) {
            spinnerBelowConsentAge.setSelection(1);
        } else {
            spinnerBelowConsentAge.setSelection(2);
        }

        if (tjPrivacyPolicy.getUsageStatsConsent() == TJStatus.TRUE) {
            spinnerUsageStatsConsent.setSelection(0);
        } else if (tjPrivacyPolicy.getUsageStatsConsent() == TJStatus.FALSE) {
            spinnerUsageStatsConsent.setSelection(1);
        } else {
            spinnerUsageStatsConsent.setSelection(2);
        }

        inputUSPrivacy.setText(tjPrivacyPolicy.getUSPrivacy());

        TJSegment segment = Tapjoy.getUserSegment();
        if (segment == TJSegment.NON_PAYER){
            spinnerUserSegment.setSelection(0);
        } else if (segment == TJSegment.PAYER){
            spinnerUserSegment.setSelection(1);
        } else if (segment == TJSegment.VIP){
            spinnerUserSegment.setSelection(2);
        } else {
            spinnerUserSegment.setSelection(3);
        }

        int userLevel = Tapjoy.getUserLevel();
        editTextUserLevel.setText(userLevel + "");

        int maxLevel = Tapjoy.getMaxLevel();
        editTextUserMaxLevel.setText(maxLevel + "");

        String userId = Tapjoy.getUserID();
        editTextUserId.setText(Objects.requireNonNullElse(userId, ""));
    }
}
