package com.tapjoy.easyapp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.tapjoy.TJError;
import com.tapjoy.TJOfferwallDiscoverView;
import com.tapjoy.TJOfferwallDiscoverListener;
import com.tapjoy.TapjoyPluginAPI;

import java.util.Locale;

public class OfferwallDiscoverFragment extends Fragment implements View.OnClickListener, TJOfferwallDiscoverListener {
    private static final String defaultPlacement = "offerwall_discover";
    private EditText placementInput;
    private TextView statusTextView;

    private EditText leftInput;
    private EditText topInput;
    private EditText widthInput;
    private EditText heightInput;

    private TJOfferwallDiscoverView offerwallDiscoverView;
    private CheckBox pluginCheckbox;

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

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

    /**
     * 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.requests_offers_button) {
                statusTextView.setText("Requested: " + placementInput.getText().toString());
                if (pluginCheckbox.isChecked()) {
                    try {
                        float left = Float.parseFloat(leftInput.getText().toString());
                        float top = Float.parseFloat(topInput.getText().toString());
                        float width = Float.parseFloat(widthInput.getText().toString());
                        float height = Float.parseFloat(heightInput.getText().toString());
                        TapjoyPluginAPI.RequestOWDiscover(requireActivity(), placementInput.getText().toString(), left, top, width, height, this);
                    } catch (NumberFormatException e) {
                        try {
                            float height = Float.parseFloat(heightInput.getText().toString());
                            TapjoyPluginAPI.RequestOWDiscover(requireActivity(), placementInput.getText().toString(), height, this);
                        } catch (NumberFormatException e2) {
                            statusTextView.setText("Invalid height value.");
                        }
                    }
                } else {
                    offerwallDiscoverView.requestContent(requireActivity(), placementInput.getText().toString());
                }
            } else if (id == R.id.Clear_offers_button) {
                if (pluginCheckbox.isChecked()) {
                    TapjoyPluginAPI.DestroyOWDiscover();
                } else {
                    offerwallDiscoverView.clearContent();
                }

                statusTextView.setText("Cleared content");
            }
        }
    }

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

        placementInput = currentView.findViewById(R.id.offers_placement_edittext);
        placementInput.setText(defaultPlacement);
        statusTextView = currentView.findViewById(R.id.offers_status_textview);

        leftInput = currentView.findViewById(R.id.left_edittext);
        topInput = currentView.findViewById(R.id.top_edittext);
        widthInput = currentView.findViewById(R.id.width_edittext);
        heightInput = currentView.findViewById(R.id.height_edittext);
        currentView.findViewById(R.id.resize_btn).setOnClickListener(new OnClickResizeListener());

        currentView.findViewById(R.id.requests_offers_button).setOnClickListener(this);
        currentView.findViewById(R.id.Clear_offers_button).setOnClickListener(this);
        pluginCheckbox = currentView.findViewById(R.id.plugin_toggle);
        pluginCheckbox.setOnCheckedChangeListener((checkbox, isChecked) -> {
            if (isChecked) {
                currentView.findViewById(R.id.position_layout).setVisibility(View.VISIBLE);
            } else {
                currentView.findViewById(R.id.position_layout).setVisibility(View.GONE);
            }
        });

        offerwallDiscoverView = currentView.findViewById(R.id.offers_webview);
        offerwallDiscoverView.setListener(this);
        offerwallDiscoverView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                float scale = getResources().getDisplayMetrics().density;

                widthInput.setText(String.format(Locale.ENGLISH, "%d", (int) (v.getWidth() / scale)));
                heightInput.setText(String.format(Locale.ENGLISH, "%d", (int) (v.getHeight() / scale)));
            }
        });
    }

    @Override
    public void requestSuccess() {
        statusTextView.setText("Request Success");
    }

    @Override
    public void requestFailure(TJError error) {
        statusTextView.setText("Request Failed: " + error.message);
    }

    @Override
    public void contentReady() {
        statusTextView.setText("Content Ready");
        if (pluginCheckbox.isChecked()) {
            TapjoyPluginAPI.ShowOWDiscover(requireActivity());
        }
    }

    @Override
    public void contentError(TJError error) {
        statusTextView.setText(String.format(Locale.ENGLISH, "Content Error: %d - %s", error.code, error.message));
    }

    private class OnClickResizeListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            float scale = getResources().getDisplayMetrics().density;
            int width = (int) (Integer.parseInt(widthInput.getText().toString()) * scale);
            int height = (int) (Integer.parseInt(heightInput.getText().toString()) * scale);
            ViewGroup.LayoutParams layoutParams = offerwallDiscoverView.getLayoutParams();
            layoutParams.width = width;
            layoutParams.height = height;
            offerwallDiscoverView.setLayoutParams(layoutParams);
        }
    }
}