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.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Patterns;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

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

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.entities.AccountCreation;
import app.fedilab.fedilabtube.helper.Helper;
import es.dmoral.toasty.Toasty;

import static app.fedilab.fedilabtube.MainActivity.PICK_INSTANCE;

public class PeertubeRegisterActivity extends AppCompatActivity {


    private Button signup;
    private TextView error_message;
    private String instance;
    private TextInputEditText login_instance;

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

        setContentView(R.layout.activity_register_peertube);

        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        signup = findViewById(R.id.signup);

        TextInputLayout login_instance_container = findViewById(R.id.login_instance_container);
        LinearLayout title_login_instance = findViewById(R.id.title_login_instance);
        TextInputEditText username = findViewById(R.id.username);
        TextInputEditText email = findViewById(R.id.email);
        TextInputEditText password = findViewById(R.id.password);
        TextInputEditText password_confirm = findViewById(R.id.password_confirm);
        login_instance = findViewById(R.id.login_instance);
        CheckBox agreement = findViewById(R.id.agreement);
        error_message = findViewById(R.id.error_message);

        if (BuildConfig.full_instances) {
            login_instance_container.setVisibility(View.VISIBLE);
            title_login_instance.setVisibility(View.VISIBLE);
        } else {
            login_instance_container.setVisibility(View.GONE);
            title_login_instance.setVisibility(View.GONE);
        }

        username.setOnFocusChangeListener((view, focused) -> {
            if (!focused && username.getText() != null) {
                Pattern patternUsername = Pattern.compile("^[a-z0-9._]{1,50}$");
                Matcher matcherMaxId = patternUsername.matcher(username.getText().toString());
                if (!matcherMaxId.matches()) {
                    username.setError(getString(R.string.username_error));
                }
            }
        });

        Button instance_help = findViewById(R.id.instance_help);

        instance_help.setOnClickListener(v -> {
            Intent intent = new Intent(PeertubeRegisterActivity.this, InstancePickerActivity.class);
            startActivityForResult(intent, PICK_INSTANCE);
        });

        email.setOnFocusChangeListener((view, focused) -> {
            if (!focused && email.getText() != null) {
                Pattern patternUsername = Patterns.EMAIL_ADDRESS;
                Matcher matcherMaxId = patternUsername.matcher(email.getText().toString());
                if (!matcherMaxId.matches()) {
                    email.setError(getString(R.string.email_error));
                }
            }
        });

        password.setOnFocusChangeListener((view, focused) -> {
            if (!focused && password.getText() != null) {
                if (password.getText().length() < 6) {
                    password.setError(getString(R.string.password_length_error));
                }
            }
        });

        password_confirm.setOnFocusChangeListener((view, focused) -> {
            if (!focused && password_confirm.getText() != null && password.getText() != null) {
                if (password_confirm.getText().toString().compareTo(password.getText().toString()) != 0) {
                    password_confirm.setError(getString(R.string.password));
                }
            }
        });
        setTextAgreement();
        signup.setOnClickListener(view -> {
            error_message.setVisibility(View.GONE);
            if (username.getText() == null || email.getText() == null || password.getText() == null || password_confirm.getText() == null || username.getText().toString().trim().length() == 0 || email.getText().toString().trim().length() == 0 ||
                    password.getText().toString().trim().length() == 0 || password_confirm.getText().toString().trim().length() == 0 || !agreement.isChecked()) {
                Toasty.error(PeertubeRegisterActivity.this, getString(R.string.all_field_filled)).show();
                return;
            }

            if (!password.getText().toString().trim().equals(password_confirm.getText().toString().trim())) {
                Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_error)).show();
                return;
            }
            if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()) {
                Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error)).show();
                return;
            }
            String[] emailArray = email.getText().toString().split("@");
            if (emailArray.length > 1 && !Arrays.asList(Helper.valideEmails).contains(emailArray[1])) {
                Toasty.error(PeertubeRegisterActivity.this, getString(R.string.email_error_domain, emailArray[1])).show();
                return;
            }

            if (password.getText().toString().trim().length() < 8) {
                Toasty.error(PeertubeRegisterActivity.this, getString(R.string.password_too_short)).show();
                return;
            }
            if (username.getText().toString().matches("[a-z0-9_]")) {
                Toasty.error(PeertubeRegisterActivity.this, getString(R.string.username_error)).show();
                return;
            }
            signup.setEnabled(false);

            if (BuildConfig.full_instances) {
                if (login_instance.getText() != null) {
                    instance = login_instance.getText().toString();
                } else {
                    instance = "";
                }
                login_instance.setOnFocusChangeListener((view1, focus) -> {
                    if (!focus) {
                        setTextAgreement();
                    }
                });
            } else {
                String host = emailArray[1];
                instance = Helper.getPeertubeUrl(host);
            }

            AccountCreation accountCreation = new AccountCreation();
            accountCreation.setEmail(email.getText().toString().trim());
            accountCreation.setPassword(password.getText().toString().trim());
            accountCreation.setPasswordConfirm(password_confirm.getText().toString().trim());
            accountCreation.setUsername(username.getText().toString().trim());
            accountCreation.setInstance(instance);

            new Thread(() -> {
                try {
                    APIResponse apiResponse = new RetrofitPeertubeAPI(PeertubeRegisterActivity.this, instance, null).createAccount(accountCreation);
                    Handler mainHandler = new Handler(Looper.getMainLooper());
                    Runnable myRunnable = () -> {
                        if (apiResponse.getError() != null) {
                            String errorMessage;
                            if (apiResponse.getError().getError() != null) {
                                try {
                                    String[] resp = apiResponse.getError().getError().split(":");
                                    if (resp.length == 2)
                                        errorMessage = apiResponse.getError().getError().split(":")[1];
                                    else if (resp.length == 3)
                                        errorMessage = apiResponse.getError().getError().split(":")[2];
                                    else
                                        errorMessage = getString(R.string.toast_error);
                                } catch (Exception e) {
                                    errorMessage = getString(R.string.toast_error);
                                }
                            } else {
                                errorMessage = getString(R.string.toast_error);
                            }
                            error_message.setText(errorMessage);
                            error_message.setVisibility(View.VISIBLE);
                            signup.setEnabled(true);
                            return;
                        }

                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PeertubeRegisterActivity.this);
                        dialogBuilder.setCancelable(false);
                        dialogBuilder.setPositiveButton(R.string.validate, (dialog, which) -> {
                            dialog.dismiss();
                            finish();
                        });
                        AlertDialog alertDialog = dialogBuilder.create();
                        alertDialog.setTitle(getString(R.string.account_created));
                        alertDialog.setMessage(getString(R.string.account_created_message, apiResponse.getStringData()));
                        alertDialog.show();
                    };
                    mainHandler.post(myRunnable);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

        });

        setTitle(R.string.create_an_account);
    }

    @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);
    }

    @SuppressLint("ApplySharedPref")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_INSTANCE && resultCode == Activity.RESULT_OK) {
            if (data != null && data.getData() != null) {
                String instance = String.valueOf(data.getData());
                login_instance.setText(instance);
                login_instance.setSelection(instance.length());
                setTextAgreement();
            }
        }
    }

    private void setTextAgreement() {
        TextView agreement_text = findViewById(R.id.agreement_text);
        String tos = getString(R.string.tos);
        String serverrules = getString(R.string.server_rules);
        String content_agreement = null;
        agreement_text.setMovementMethod(null);
        agreement_text.setText(null);
        if (BuildConfig.full_instances) {
            if (login_instance.getText() != null) {
                content_agreement = getString(R.string.agreement_check_peertube,
                        "<a href='https://" + login_instance.getText().toString() + "/about/instance#terms-section' >" + tos + "</a>"
                );
            }
        } else {
            content_agreement = getString(R.string.agreement_check,
                    "<a href='https://apps.education.fr/cgu#peertube' >" + serverrules + "</a>",
                    "<a href='https://apps.education.fr/bonnes-pratiques/' >" + tos + "</a>"
            );
        }
        agreement_text.setMovementMethod(LinkMovementMethod.getInstance());
        if (content_agreement != null) {
            agreement_text.setText(Html.fromHtml(content_agreement));
        }
    }

}