package app.fedilab.android.activities;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import com.github.stom79.localepicker.CountryPicker;
import com.github.stom79.mytransl.MyTransL;
import com.github.stom79.mytransl.client.HttpsConnectionException;
import com.github.stom79.mytransl.translate.Translate;
import com.vanniktech.emoji.EmojiPopup;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import app.fedilab.android.R;
import app.fedilab.android.helper.Helper;
import es.dmoral.toasty.Toasty;

/* Copyright 2020 Thomas Schneider
 *
 * This file is a part of Fedilab
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with Fedilab; if not,
 * see <http://www.gnu.org/licenses>. */

public class TootActivity extends BaseTootActivity {

    private AlertDialog dialogTrans;

    @Override
    protected boolean actionTranslateClick() {

        SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE);
        final CountryPicker picker = CountryPicker.newInstance(getString(R.string.which_language));  // dialog title
        if (theme == Helper.THEME_LIGHT) {
            picker.setStyle(DialogFragment.STYLE_NO_TITLE, R.style.Dialog);
        } else {
            picker.setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogDark);
        }
        if (toot_content.getText().length() == 0 && toot_cw_content.getText().length() == 0)
            return true;
        String dateString = sharedpreferences.getString(Helper.LAST_TRANSLATION_TIME, null);
        if (dateString != null) {
            Date dateCompare = Helper.stringToDate(TootActivity.this, dateString);
            Date date = new Date();
            if (date.before(dateCompare)) {
                Toasty.info(TootActivity.this, getString(R.string.please_wait), Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        picker.setListener((name, locale, flagDrawableResID) -> {
            picker.dismiss();
            AlertDialog.Builder transAlert = new AlertDialog.Builder(TootActivity.this, style);
            transAlert.setTitle(R.string.translate_toot);

            View popup_trans = getLayoutInflater().inflate(R.layout.popup_translate, new LinearLayout(TootActivity.this), false);
            transAlert.setView(popup_trans);
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(Helper.LAST_TRANSLATION_TIME, Helper.dateToString(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(Helper.SECONDES_BETWEEN_TRANSLATE))));
            editor.apply();
            TextView yandex_translate = popup_trans.findViewById(R.id.yandex_translate);
            yandex_translate.setOnClickListener(v -> {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://translate.yandex.com/"));
                startActivity(browserIntent);
            });
            MyTransL myTransL = MyTransL.getInstance(MyTransL.translatorEngine.YANDEX);
            myTransL.setYandexAPIKey(Helper.YANDEX_KEY);
            myTransL.setObfuscation(true);
            myTransL.setTimeout(60);
            if (toot_cw_content.getText().toString().length() > 0)
                myTransL.translate(toot_cw_content.getText().toString(), locale, new com.github.stom79.mytransl.client.Results() {
                    @Override
                    public void onSuccess(Translate translate) {
                        try {
                            if (translate.getTranslatedContent() == null)
                                return;
                            ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw);
                            ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot);
                            if (trans_progress_cw != null)
                                trans_progress_cw.setVisibility(View.GONE);
                            LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container);
                            if (trans_container != null) {
                                TextView cw_trans = popup_trans.findViewById(R.id.cw_trans);
                                if (cw_trans != null) {
                                    cw_trans.setVisibility(View.VISIBLE);
                                    cw_trans.setText(translate.getTranslatedContent());
                                }
                            } else {
                                Toasty.error(TootActivity.this, getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show();
                            }
                            if (trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE)
                                if (dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null)
                                    dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true);
                        } catch (IllegalArgumentException e) {
                            Toasty.error(TootActivity.this, getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show();
                        }

                    }

                    @Override
                    public void onFail(HttpsConnectionException e) {
                        e.printStackTrace();
                    }
                });
            else {
                ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw);
                trans_progress_cw.setVisibility(View.GONE);
            }
            if (toot_content.getText().toString().length() > 0)
                myTransL.translate(toot_content.getText().toString(), locale, new com.github.stom79.mytransl.client.Results() {
                    @Override
                    public void onSuccess(Translate translate) {
                        try {
                            if (translate.getTranslatedContent() == null)
                                return;
                            ProgressBar trans_progress_cw = popup_trans.findViewById(R.id.trans_progress_cw);
                            ProgressBar trans_progress_toot = popup_trans.findViewById(R.id.trans_progress_toot);
                            if (trans_progress_toot != null)
                                trans_progress_toot.setVisibility(View.GONE);
                            LinearLayout trans_container = popup_trans.findViewById(R.id.trans_container);
                            if (trans_container != null) {
                                TextView toot_trans = popup_trans.findViewById(R.id.toot_trans);
                                if (toot_trans != null) {
                                    toot_trans.setVisibility(View.VISIBLE);
                                    toot_trans.setText(translate.getTranslatedContent());
                                }
                            } else {
                                Toasty.error(TootActivity.this, getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show();
                            }
                            if (trans_progress_cw != null && trans_progress_toot != null && trans_progress_cw.getVisibility() == View.GONE && trans_progress_toot.getVisibility() == View.GONE)
                                if (dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE) != null)
                                    dialogTrans.getButton(DialogInterface.BUTTON_NEGATIVE).setEnabled(true);
                        } catch (IllegalArgumentException e) {
                            Toasty.error(TootActivity.this, getString(R.string.toast_error_translate), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFail(HttpsConnectionException e) {
                        e.printStackTrace();
                    }
                });

            transAlert.setPositiveButton(R.string.close, (dialog, whichButton) -> dialog.dismiss());
            transAlert.setNegativeButton(R.string.validate, (dialog, whichButton) -> {
                TextView toot_trans = popup_trans.findViewById(R.id.toot_trans);
                TextView cw_trans = popup_trans.findViewById(R.id.cw_trans);
                if (toot_trans != null) {
                    toot_content.setText(toot_trans.getText().toString());
                    toot_content.setSelection(toot_content.getText().length());
                }
                if (cw_trans != null)
                    toot_cw_content.setText(cw_trans.getText().toString());
                dialog.dismiss();
            });
            dialogTrans = transAlert.create();
            transAlert.show();

            dialogTrans.setOnShowListener(dialog -> {
                Button negativeButton = ((AlertDialog) dialog)
                        .getButton(AlertDialog.BUTTON_NEGATIVE);
                if (negativeButton != null)
                    negativeButton.setEnabled(false);
            });

        });
        picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
        return true;
    }


    @Override
    protected void launchPhotoEditor(Uri uri) {
        Intent intent = new Intent(TootActivity.this, PhotoEditorActivity.class);
        Bundle b = new Bundle();
        intent.putExtra("imageUri", uri.toString());
        intent.putExtras(b);
        startActivity(intent);
    }

    @Override
    protected void displayEmojiPopup() {
        final EmojiPopup emojiPopup = EmojiPopup.Builder.fromRootView(drawer_layout).build(toot_content);

        toot_emoji.setOnClickListener(v -> {
            emojiPopup.toggle(); // Toggles visibility of the Popup.
        });
    }
}
