package app.fedilab.fedilabtube;
/* Copyright 2020 Thomas Schneider
 *
 * This file is a part of TubeLab
 *
 * 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.
 *
 * TubeLab 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 TubeLab; if not,
 * see <http://www.gnu.org/licenses>. */

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.Arrays;

import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.entities.Error;
import app.fedilab.fedilabtube.client.entities.Oauth;
import app.fedilab.fedilabtube.client.entities.OauthParams;
import app.fedilab.fedilabtube.client.entities.Token;
import app.fedilab.fedilabtube.helper.Helper;
import es.dmoral.toasty.Toasty;

import static app.fedilab.fedilabtube.client.RetrofitPeertubeAPI.updateCredential;


public class LoginActivity extends AppCompatActivity {


    private static String client_id;
    private static String client_secret;
    private EditText login_uid;
    private EditText login_passwd;
    private Button connectionButton;
    private TextInputEditText login_instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_login);
        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        TextView create_an_account_peertube = findViewById(R.id.create_an_account_peertube);

        SpannableString content_create = new SpannableString(getString(R.string.join_peertube));
        content_create.setSpan(new UnderlineSpan(), 0, content_create.length(), 0);
        content_create.setSpan(new ForegroundColorSpan(ContextCompat.getColor(LoginActivity.this, Helper.getColorAccent())), 0, content_create.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        create_an_account_peertube.setText(content_create);

        create_an_account_peertube.setOnClickListener(v -> {
            Intent mainActivity = new Intent(LoginActivity.this, PeertubeRegisterActivity.class);
            Bundle b = new Bundle();
            mainActivity.putExtras(b);
            startActivity(mainActivity);
        });


        TextInputLayout login_instance_container = findViewById(R.id.login_instance_container);
        login_instance = findViewById(R.id.login_instance);
        if (BuildConfig.full_instances) {
            login_instance_container.setVisibility(View.VISIBLE);
        }

        login_uid = findViewById(R.id.login_uid);
        login_passwd = findViewById(R.id.login_passwd);

        if (Helper.isTablet(LoginActivity.this)) {
            TextInputLayout login_uid_container = findViewById(R.id.login_uid_container);
            ViewGroup.LayoutParams layoutParamsU = login_uid_container.getLayoutParams();
            layoutParamsU.width = (int) Helper.convertDpToPixel(300, LoginActivity.this);
            login_uid_container.setLayoutParams(layoutParamsU);

            TextInputLayout login_passwd_container = findViewById(R.id.login_passwd_container);
            ViewGroup.LayoutParams layoutParamsP = login_passwd_container.getLayoutParams();
            layoutParamsP.width = (int) Helper.convertDpToPixel(300, LoginActivity.this);
            login_passwd_container.setLayoutParams(layoutParamsP);
        }


        connectionButton = findViewById(R.id.login_button);

        if (!BuildConfig.full_instances) {
            login_uid.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    if (android.util.Patterns.EMAIL_ADDRESS.matcher(login_uid.getText().toString().trim()).matches()) {
                        String[] emailArray = login_uid.getText().toString().split("@");
                        if (emailArray.length > 1 && Arrays.asList(Helper.openid).contains(emailArray[1])) {
                            connectionButton.callOnClick();
                        }
                    }
                }
            });
        }


        connectionButton.setOnClickListener(v -> {

            if (login_uid.getText().toString().contains("@") && !android.util.Patterns.EMAIL_ADDRESS.matcher(login_uid.getText().toString().trim()).matches()) {
                Toasty.error(LoginActivity.this, getString(R.string.email_error)).show();
                return;
            }
            connectionButton.setEnabled(false);
            String instance, host;
            if (!BuildConfig.full_instances) {
                String[] emailArray = login_uid.getText().toString().split("@");
                if (emailArray.length > 1 && !Arrays.asList(Helper.valideEmails).contains(emailArray[1])) {
                    Toasty.error(LoginActivity.this, getString(R.string.email_error_domain, emailArray[1])).show();
                    return;
                }
                host = emailArray[1];
                instance = Helper.getPeertubeUrl(host);
            } else {
                if (login_instance == null || login_instance.getText() == null || login_instance.getText().toString().trim().length() == 0) {
                    Toasty.error(LoginActivity.this, getString(R.string.not_valide_instance)).show();
                    return;
                }
                instance = host = login_instance.getText().toString().trim().toLowerCase();
            }
            if (Arrays.asList(Helper.openid).contains(host) && !BuildConfig.full_instances) {
                new Thread(() -> {
                    try {
                        Oauth oauth = new RetrofitPeertubeAPI(LoginActivity.this, instance, null).oauthClient(null, null, null, null);
                        if (oauth == null) {
                            runOnUiThread(() -> {
                                connectionButton.setEnabled(true);
                                Toasty.error(LoginActivity.this, getString(R.string.client_error), Toast.LENGTH_LONG).show();
                            });
                            return;
                        }
                        client_id = oauth.getClient_id();
                        client_secret = oauth.getClient_secret();
                        SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedpreferences.edit();
                        editor.putString(Helper.CLIENT_ID, client_id);
                        editor.putString(Helper.CLIENT_SECRET, client_secret);
                        editor.apply();
                        Intent intent = new Intent(LoginActivity.this, WebviewConnectActivity.class);
                        Bundle b = new Bundle();
                        b.putString("url", "https://" + Helper.getPeertubeUrl(host) + "/plugins/auth-openid-connect/0.0.1/auth/openid-connect");
                        intent.putExtras(b);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            connectionButton.setEnabled(true);
                            Toasty.error(LoginActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
                        });
                    }

                }).start();
            } else {
                new Thread(() -> {
                    Oauth oauth = new RetrofitPeertubeAPI(LoginActivity.this, instance, null).oauthClient(Helper.CLIENT_NAME_VALUE, Helper.WEBSITE_VALUE, Helper.OAUTH_SCOPES_PEERTUBE, Helper.WEBSITE_VALUE);
                    if (oauth == null) {
                        runOnUiThread(() -> {
                            connectionButton.setEnabled(true);
                            Toasty.error(LoginActivity.this, getString(R.string.client_error), Toast.LENGTH_LONG).show();
                        });
                        return;
                    }

                    client_id = oauth.getClient_id();
                    client_secret = oauth.getClient_secret();

                    SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(Helper.CLIENT_ID, client_id);
                    editor.putString(Helper.CLIENT_SECRET, client_secret);
                    editor.apply();
                    OauthParams oauthParams = new OauthParams();
                    oauthParams.setClient_id(client_id);
                    oauthParams.setClient_secret(client_secret);
                    oauthParams.setGrant_type("password");
                    oauthParams.setScope("user");
                    oauthParams.setUsername(login_uid.getText().toString().trim());
                    oauthParams.setPassword(login_passwd.getText().toString());
                    try {
                        Token token = new RetrofitPeertubeAPI(LoginActivity.this, instance, null).manageToken(oauthParams);
                        proceedLogin(token, host);
                    } catch (final Exception | Error e) {
                        oauthParams.setUsername(login_uid.getText().toString().toLowerCase().trim());
                        try {
                            Token token = new RetrofitPeertubeAPI(LoginActivity.this, instance, null).manageToken(oauthParams);
                            proceedLogin(token, host);
                        } catch (Error error) {
                            Error.displayError(LoginActivity.this, error);
                            error.printStackTrace();
                        }
                    }
                }).start();
            }

        });
    }

    @SuppressLint("ApplySharedPref")
    private void proceedLogin(Token token, String host) {
        runOnUiThread(() -> {
            if (token != null) {
                SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, token.getAccess_token());
                editor.putString(Helper.PREF_INSTANCE, host);
                editor.commit();
                //Update the account with the token;
                updateCredential(LoginActivity.this, token.getAccess_token(), client_id, client_secret, token.getRefresh_token(), host);
            } else {
                connectionButton.setEnabled(true);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


}