package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.app.NotificationCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.LanguageResponse;
import com.cygnusa.hyperm.wrappers.Languages;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SettingsActivity extends AppCompatActivity {
    ApiService restService;
    TransparentProgressDialog progressDialog;
    TextView mTextLanguageSelection;
    ImageView mImageLangSelection;
    private AlertDialog.Builder builder;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    ArrayList<Languages> MY_CONTENTS = new ArrayList<>();
    ArrayList<String> LanguageList = new ArrayList<>();
    ArrayList<String> LanguageCode = new ArrayList<>();
    String language;
    LinearLayout layoutLanguage;
    String userType;
    Switch notificationSound,notificationVibrate;
    boolean vibrate,sound;
    private NotificationManager notificationManager;
    private NotificationCompat.Builder notificationBuilder;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        setupWindowAnimations();
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            userType = extras.getString("usertype");
        }
        restService = ((MainApplication) getApplication()).getClient();
        mTextLanguageSelection = findViewById(R.id.textLanguage);
        mImageLangSelection = findViewById(R.id.imgLanguage);
        layoutLanguage = findViewById(R.id.layout);
        language = this.getSharedPreferences("LANGUAGE", Context.MODE_PRIVATE).getString("DEFAULT", "en_us");
        if (userType.equalsIgnoreCase("am")) {
            layoutLanguage.setVisibility(View.GONE);
        }
        mTextLanguageSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLanguageSelectionList();
            }
        });
        mImageLangSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTextLanguageSelection.performClick();
            }
        });
        getLanguageContents();

        preferences = getApplicationContext().getSharedPreferences("MySettings", 0); // 0 - for private mode
        editor = preferences.edit();

        notificationSound = (Switch) findViewById(R.id.notificationSoundSwitch);
        notificationSound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (buttonView.isChecked()){
                    editor.putBoolean("sound", true);
                    editor.commit();
                }
                else{
                    editor.putBoolean("sound", false);
                    editor.commit();
                }
            }
        });
        notificationVibrate = (Switch) findViewById(R.id.notificationVibrateSwitch);
        notificationVibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (buttonView.isChecked()){
                    editor.putBoolean("vibrate", true);
                    editor.commit();
                }
                else{
                    editor.putBoolean("vibrate", false);
                    editor.commit();
                }
            }
        });
        preferences = getSharedPreferences("MySettings",
                Context.MODE_PRIVATE);
        if(preferences.getBoolean("vibrate",true)){
            notificationVibrate.setChecked(true);
        }else {
            notificationVibrate.setChecked(false);
        }

        if(preferences.getBoolean("sound",true)){
            notificationSound.setChecked(true);
        }else {
            notificationSound.setChecked(false);
        }


        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
    }

    private void getLanguageContents() {
        if (new UtilService().isNetworkAvailable(SettingsActivity.this)) {

            progressDialog = new TransparentProgressDialog(SettingsActivity.this);
            progressDialog.show();


            restService.getLanguage().enqueue(new Callback<LanguageResponse>() {
                @Override
                public void onResponse(Call<LanguageResponse> call, Response<LanguageResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }


                    if (response.body() != null && response.body().getStatus() == 200) {


                        MY_CONTENTS = response.body().getData();
                        setLanguageList();
                        for (int i = 0; i < LanguageCode.size(); i++) {
                            if (LanguageCode.get(i).equalsIgnoreCase(language)) {
                                mTextLanguageSelection.setText(LanguageList.get(i).trim());
                            }
                        }
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        }
                    }

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (getPreferences(MODE_PRIVATE).getBoolean("ContentListActivity", true)) {
                                // showHelpScreen();
                                getPreferences(MODE_PRIVATE).edit().putBoolean("ContentListActivity", false).apply();
                            }
                        }
                    }, 1000);
                }

                @Override
                public void onFailure(Call<LanguageResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    private void setLanguageList() {
        LanguageList.clear();
        LanguageCode.clear();
        for (int i = 0; i < MY_CONTENTS.size(); i++) {
            LanguageList.add(MY_CONTENTS.get(i).getLanguage_title());
            LanguageCode.add(MY_CONTENTS.get(i).getLanguage_code());
        }
    }

    private static NotificationCompat.Builder buildNotificationCommon(Context _context) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
                .setWhen(System.currentTimeMillis());
        //Vibration
        builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

        //LED
        builder.setLights(Color.RED, 3000, 3000);

        //Ton
      //  builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));

        return builder;
    }
    private void beep(int volume)
    {
        AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
        Uri notification = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        MediaPlayer player = MediaPlayer.create(getApplicationContext(), notification);
        player.start();
    }
    private void showLanguageSelectionList() {

        builder = new AlertDialog.Builder(SettingsActivity.this);
        builder.setTitle("SELECT LANGUAGE")
                .setItems(LanguageList.toArray(new String[LanguageList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        preferences = getSharedPreferences("LANGUAGE",
                                Context.MODE_PRIVATE);
                        editor = preferences.edit();
                        editor.putString("DEFAULT", LanguageCode.get(i));
                        mTextLanguageSelection.setText(LanguageList.get(i));
                        editor.apply();
                        dialogInterface.dismiss();
                    }
                });

        builder.create().show();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }
}

