package com.smaato.sdk.demoapp;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.smaato.sdk.core.Gender;
import com.smaato.sdk.core.SmaatoSdk;
import com.smaato.sdk.demoapp.utils.ClickListener;
import com.smaato.sdk.demoapp.utils.PreferencesUtils;

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

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static com.smaato.sdk.demoapp.utils.PreferencesUtils.KEY_AGE;
import static com.smaato.sdk.demoapp.utils.PreferencesUtils.KEY_GENDER;
import static com.smaato.sdk.demoapp.utils.PreferencesUtils.KEY_KEYWORDS;

public class SettingsActivity extends AppCompatActivity {

    private static final String TAG = "SettingsActivity";

    private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;

    private EditText editTextKeywords;
    private EditText editTextAge;
    private Spinner spinnerGender;
    private TextView viewLocationPermissionStatus;
    private Button requestLocationPermissionButton;
    private SwitchCompat switchLogging;
    private SwitchCompat switchDebug;
    private SharedPreferences preferences;

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

        preferences = PreferencesUtils.getPrefs(this);

        editTextKeywords = findViewById(R.id.keywords);
        editTextAge = findViewById(R.id.age);
        spinnerGender = findViewById(R.id.gender);

        viewLocationPermissionStatus = findViewById(R.id.permission_status);
        requestLocationPermissionButton = findViewById(R.id.request_permission);

        switchLogging = findViewById(R.id.logging);
        switchDebug = findViewById(R.id.debug);

        editTextKeywords.setText(preferences.getString(KEY_KEYWORDS, ""));

        initAgeEditText();
        initGenderSpinner(savedInstanceState == null);
        initRequestLocationPermissionButton();
        switchLogging.setEnabled(false); // out of scope for MVP1
        switchDebug.setEnabled(false);   // out of scope for MVP1
    }

    @SuppressLint("ApplySharedPref")
    @Override
    public void onBackPressed() {
        super.onBackPressed();

        final SharedPreferences.Editor editor = preferences.edit();

        String keywords = editTextKeywords.getText().toString().trim();
        if (keywords.isEmpty()) {
            editor.remove(KEY_KEYWORDS);
        } else {
            editor.putString(KEY_KEYWORDS, keywords);
        }

        String age = editTextAge.getText().toString().trim();
        if (age.isEmpty()) {
            editor.remove(KEY_AGE);
        } else {
            Integer ageInteger = null;
            try {
                ageInteger = Integer.valueOf(age);
            } catch (NumberFormatException e) {
                Log.e(TAG, "unable to parse age", e);
            }
            if (ageInteger == null) {
                editor.remove(KEY_AGE);
            } else {
                editor.putString(KEY_AGE, ageInteger.toString());
            }
        }

        int selectedGenderPosition = spinnerGender.getSelectedItemPosition();
        if (selectedGenderPosition == Spinner.INVALID_POSITION) {
            editor.remove(KEY_GENDER);
        } else {
            editor.putInt(KEY_GENDER, selectedGenderPosition - 1);
        }

        editor.commit();

        applySettingsToSdk();
    }

    private void applySettingsToSdk() {
        // apply keywords
        SmaatoSdk.setKeywords(preferences.getString(KEY_KEYWORDS, null));

        // apply age
        Integer age = null;
        try {
            age = Integer.valueOf(preferences.getString(KEY_AGE, null));
        } catch (NumberFormatException ignored) {
        }
        SmaatoSdk.setAge(age);

        // apply gender
        Gender gender = null;
        try {
            gender = Gender.values()[preferences.getInt(KEY_GENDER, -1)];
        } catch (ArrayIndexOutOfBoundsException ignored) {
        }
        SmaatoSdk.setGender(gender);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_LOCATION_PERMISSION) {
            updateLocationPermissionUI();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            updateLocationPermissionUI();
        }
    }

    private void initRequestLocationPermissionButton() {
        requestLocationPermissionButton.setOnClickListener(requestLocationPermissionButtonListener);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            viewLocationPermissionStatus.setText(R.string.location_permission_status_on);
            viewLocationPermissionStatus.setTextColor(getResources().getColor(R.color.colorAccent));
            requestLocationPermissionButton.setEnabled(false);
        }
    }

    private void initAgeEditText() {
        editTextAge.setText(preferences.getString(KEY_AGE, ""));
        InputFilter[] initialEditTextKeywordsFilters = editTextAge.getFilters();
        InputFilter[] editTextKeywordsFilters = Arrays.copyOf(initialEditTextKeywordsFilters, initialEditTextKeywordsFilters.length + 1);
        editTextKeywordsFilters[editTextKeywordsFilters.length - 1] = new InputFilter.LengthFilter(3);
        editTextAge.setFilters(editTextKeywordsFilters);
    }

    private void initGenderSpinner(boolean initPosition) {
        final ArrayList<String> items = new ArrayList<>();
        items.add(getString(R.string.gender)); // hint
        for (Gender gender : Gender.values()) {
            items.add(gender.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);

        spinnerGender.setAdapter(adapter);

        if (initPosition) {
            int currentGenderOrdinal = preferences.getInt(KEY_GENDER, -1);
            if (currentGenderOrdinal >= 0 && currentGenderOrdinal < Gender.values().length) {
                spinnerGender.setSelection(currentGenderOrdinal + 1);
            }
        }
    }

    private boolean hasPermission(@NonNull String permission) {
        return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void updateLocationPermissionUI() {
        boolean hasPermission = hasPermission(ACCESS_COARSE_LOCATION);
        viewLocationPermissionStatus.setText(hasPermission ? R.string.location_permission_status_on : R.string.location_permission_status_off);
        viewLocationPermissionStatus.setTextColor(getResources().getColor(hasPermission ? R.color.colorAccent : android.R.color.darker_gray, getTheme()));
        requestLocationPermissionButton.setEnabled(!hasPermission);
        requestLocationPermissionButtonListener.reset();
    }

    private final ClickListener requestLocationPermissionButtonListener = new ClickListener() {

        private final String[] permissions = {ACCESS_COARSE_LOCATION};

        @Override
        public void handleClick(@NonNull View v) {
            ActivityCompat.requestPermissions(SettingsActivity.this, permissions, REQUEST_CODE_LOCATION_PERMISSION);
        }
    };
}
