package com.smaato.sdk.demoapp.banner;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.smaato.sdk.banner.ad.BannerAdSize;
import com.smaato.sdk.demoapp.R;
import com.smaato.sdk.demoapp.utils.BaseTextWatcher;

import java.util.ArrayList;
import java.util.Arrays;

public class CreateBannerAdConfigActivity extends AppCompatActivity {

    public static final String NEW_CONFIG = "new_config";
    public static final String OLD_CONFIG = "old_config";

    private static final int MAX_INPUT_LENGTH_ID = 20;
    private static final int MAX_INPUT_LENGTH_NAME = 30;

    @NonNull
    private EditText editTextAdSpaceId;
    @NonNull
    private EditText editTextPublisherId;
    @NonNull
    private Spinner spinnerBannerAdSize;
    @NonNull
    private EditText editTextName;
    @Nullable
    private BannerAdConfig oldAdConfig;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_banner_ad_config);

        editTextAdSpaceId = findViewById(R.id.adspace_id);
        editTextPublisherId = findViewById(R.id.publisher_id);
        spinnerBannerAdSize = findViewById(R.id.banner_ad_size);
        editTextName = findViewById(R.id.name);

        if (getIntent() != null) {
            oldAdConfig = getIntent().getParcelableExtra(OLD_CONFIG);
        }

        String adSpace = oldAdConfig != null ? oldAdConfig.adSpaceId : "";
        String publisherId = oldAdConfig != null ? oldAdConfig.publisherId : "";
        String name = oldAdConfig != null ? oldAdConfig.name : "";
        BannerAdSize bannerAdSize = oldAdConfig != null ? oldAdConfig.bannerAdSize : null;

        initEditText(editTextAdSpaceId, MAX_INPUT_LENGTH_ID, textWatcher, adSpace);
        initEditText(editTextPublisherId, MAX_INPUT_LENGTH_ID, textWatcher, publisherId);
        initEditText(editTextName, MAX_INPUT_LENGTH_NAME, textWatcher, name);

        initBannerAdSizeSpinner(bannerAdSize);

        supportInvalidateOptionsMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.create_custom_ad_config_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean isDataValid = true;

        for (EditText editText : Arrays.asList(editTextName, editTextPublisherId, editTextAdSpaceId)) {
            if (editText.getText().toString().trim().isEmpty()) {
                isDataValid = false;
                break;
            }
        }

        if (isDataValid) {
            int bannerAdSizeOrdinal = spinnerBannerAdSize.getSelectedItemPosition() - 1;
            if (bannerAdSizeOrdinal < 0 || bannerAdSizeOrdinal >= BannerAdSize.values().length) {
                isDataValid = false;
            }
        }

        menu.findItem(R.id.save).setEnabled(isDataValid);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.save:
                Intent data = new Intent();
                data.putExtra(NEW_CONFIG, new BannerAdConfig(
                        editTextName.getText().toString().trim(),
                        editTextPublisherId.getText().toString().trim(),
                        editTextAdSpaceId.getText().toString().trim(),
                        BannerAdSize.values()[spinnerBannerAdSize.getSelectedItemPosition() - 1]));
                data.putExtra(OLD_CONFIG, oldAdConfig);
                setResult(RESULT_OK, data);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private static void initEditText(@NonNull EditText editText, int maxLength, @NonNull TextWatcher textWatcher, @NonNull String value) {
        InputFilter[] initialEditTextKeywordsFilters = editText.getFilters();
        InputFilter[] editTextKeywordsFilters = Arrays.copyOf(initialEditTextKeywordsFilters, initialEditTextKeywordsFilters.length + 1);
        editTextKeywordsFilters[editTextKeywordsFilters.length - 1] = new InputFilter.LengthFilter(maxLength);
        editText.setFilters(editTextKeywordsFilters);
        editText.addTextChangedListener(textWatcher);
        editText.setText(value);
    }

    private void initBannerAdSizeSpinner(@Nullable BannerAdSize oldBannerAdSize) {
        final ArrayList<String> items = new ArrayList<>();
        items.add(getString(R.string.size)); // hint
        for (BannerAdSize bannerAdSize : BannerAdSize.values()) {
            items.add(bannerAdSize.toString());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items) {
            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView view = (TextView) super.getDropDownView(position, convertView, parent);
                view.setTextColor(isHintPosition(position) ? Color.GRAY : Color.BLACK);
                return view;
            }

            private boolean isHintPosition(int position) {
                return position == 0;
            }
        };

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinnerBannerAdSize.setAdapter(adapter);
        spinnerBannerAdSize.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                supportInvalidateOptionsMenu();
            }
        });

        if (oldBannerAdSize != null) {
            spinnerBannerAdSize.setSelection(adapter.getPosition(oldBannerAdSize.toString()));
        }
    }

    private final TextWatcher textWatcher = new BaseTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            supportInvalidateOptionsMenu();
        }
    };
}
