/* Copyright 2017 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>. */
package app.fedilab.android.activities;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import app.fedilab.android.R;
import app.fedilab.android.asynctasks.RetrieveAccountInfoAsyncTask;
import app.fedilab.android.asynctasks.UpdateAccountInfoAsyncTask;
import app.fedilab.android.asynctasks.UpdateCredentialAsyncTask;
import app.fedilab.android.client.API;
import app.fedilab.android.client.APIResponse;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.client.Entities.Error;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.interfaces.OnRetrieveAccountInterface;
import app.fedilab.android.interfaces.OnUpdateCredentialInterface;
import app.fedilab.android.sqlite.AccountDAO;
import app.fedilab.android.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;


/**
 * Created by Thomas on 27/08/2017.
 * Edit profile activity
 */

public class EditProfileActivity extends BaseActivity implements OnRetrieveAccountInterface, OnUpdateCredentialInterface {


    private static final int PICK_IMAGE_HEADER = 4565;
    private static final int PICK_IMAGE_PROFILE = 6545;
    private final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_HEADER = 754;
    private final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_PICTURE = 755;
    private EditText set_profile_name, set_profile_description;
    private ImageView set_profile_picture, set_header_picture;
    private Button set_change_profile_picture, set_change_header_picture, set_profile_save;
    private TextView set_header_picture_overlay;
    private CheckBox set_lock_account, set_sensitive_content;
    private String profile_username, profile_note;
    private ByteArrayInputStream profile_picture, header_picture;
    private API.accountPrivacy profile_privacy;
    private boolean sensitive;
    private Bitmap profile_picture_bmp, profile_header_bmp;
    private ImageView pp_actionBar;
    private String avatarName, headerName;

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

        SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
        int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
        switch (theme) {
            case Helper.THEME_LIGHT:
                setTheme(R.style.AppTheme_Fedilab);
                break;
            case Helper.THEME_BLACK:
                setTheme(R.style.AppThemeBlack);
                break;
            default:
                setTheme(R.style.AppThemeDark);
        }

        setContentView(R.layout.activity_edit_profile);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
            assert inflater != null;
            View view = inflater.inflate(R.layout.simple_action_bar, new LinearLayout(EditProfileActivity.this), false);
            view.setBackground(new ColorDrawable(ContextCompat.getColor(EditProfileActivity.this, R.color.cyanea_primary)));
            actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
            pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar);
            title.setText(R.string.settings_title_profile);
            ImageView close_conversation = actionBar.getCustomView().findViewById(R.id.close_conversation);
            if (close_conversation != null) {
                close_conversation.setOnClickListener(v -> finish());
            }
        } else {
            setTitle(R.string.settings_title_profile);
        }
        SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
        String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
        String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, null);
        Account account = new AccountDAO(EditProfileActivity.this, db).getUniqAccount(userId, instance);


        Helper.loadGiF(EditProfileActivity.this, account, pp_actionBar);
        LinearLayout custom_fields_container = findViewById(R.id.custom_fields_container);
        set_profile_name = findViewById(R.id.set_profile_name);
        set_profile_description = findViewById(R.id.set_profile_description);
        set_profile_picture = findViewById(R.id.set_profile_picture);
        set_header_picture = findViewById(R.id.set_header_picture);
        set_change_profile_picture = findViewById(R.id.set_change_profile_picture);
        set_change_header_picture = findViewById(R.id.set_change_header_picture);
        set_profile_save = findViewById(R.id.set_profile_save);
        set_header_picture_overlay = findViewById(R.id.set_header_picture_overlay);
        set_lock_account = findViewById(R.id.set_lock_account);
        set_sensitive_content = findViewById(R.id.set_sensitive_content);

        set_lock_account.setVisibility(View.VISIBLE);
        set_sensitive_content.setVisibility(View.VISIBLE);

        if (account.getSocial().toUpperCase().equals("MASTODON")) {
            custom_fields_container.setVisibility(View.VISIBLE);
        }

        set_profile_save.setEnabled(false);
        set_change_header_picture.setEnabled(false);
        set_change_profile_picture.setEnabled(false);
        set_profile_name.setEnabled(false);
        set_profile_description.setEnabled(false);
        set_lock_account.setEnabled(false);
        set_sensitive_content.setEnabled(false);
        new RetrieveAccountInfoAsyncTask(EditProfileActivity.this, EditProfileActivity.this).execute();

    }

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


    @SuppressLint("CutPasteId")
    @Override
    public void onRetrieveAccount(Account account, Error error) {
        if (error != null) {
            Toasty.error(EditProfileActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
            return;
        }
        set_profile_name.setText(account.getDisplay_name());
        set_profile_name.setSelection(set_profile_name.getText().length());

        String content = account.getNote();
        if (content != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                content = Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString();
            else
                content = Html.fromHtml(content).toString();
        } else
            content = "";
        set_profile_description.setText(content);

        set_profile_save.setEnabled(true);
        set_change_header_picture.setEnabled(true);
        set_change_profile_picture.setEnabled(true);
        set_profile_name.setEnabled(true);
        set_profile_description.setEnabled(true);
        set_lock_account.setEnabled(true);
        set_sensitive_content.setEnabled(true);
        if (account.isLocked())
            set_lock_account.setChecked(true);
        else
            set_lock_account.setChecked(false);
        if (account.isSensitive())
            set_sensitive_content.setChecked(true);
        else
            set_sensitive_content.setChecked(false);
        set_profile_description.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int maxChar = 160;
                if (MainActivity.social == UpdateAccountInfoAsyncTask.SOCIAL.PLEROMA) {
                    maxChar = 500;
                }
                if (s.length() > maxChar) {
                    String content = s.toString().substring(0, maxChar);
                    set_profile_description.setText(content);
                    set_profile_description.setSelection(set_profile_description.getText().length());
                    Toasty.info(EditProfileActivity.this, getString(R.string.note_no_space), Toast.LENGTH_LONG).show();
                }
            }
        });
        if (account.getFields() != null && account.getFields().size() > 0) {
            HashMap<String, String> fields = account.getFields();
            Iterator it = fields.entrySet().iterator();
            int i = 1;
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry) it.next();
                String label = (String) pair.getKey();
                String value = (String) pair.getValue();
                EditText labelView;
                EditText valueView;
                switch (i) {
                    case 2:
                        labelView = findViewById(R.id.cf_key_2);
                        valueView = findViewById(R.id.cf_val_2);
                        break;
                    case 3:
                        labelView = findViewById(R.id.cf_key_3);
                        valueView = findViewById(R.id.cf_val_3);
                        break;
                    case 4:
                        labelView = findViewById(R.id.cf_key_4);
                        valueView = findViewById(R.id.cf_val_4);
                        break;
                    default:
                        labelView = findViewById(R.id.cf_key_1);
                        valueView = findViewById(R.id.cf_val_1);
                        break;
                }
                labelView.setText(label);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    value = Html.fromHtml(value, Html.FROM_HTML_MODE_LEGACY).toString();
                else
                    value = Html.fromHtml(value).toString();
                valueView.setText(value);
                i++;
            }
        }

        set_profile_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 30) {
                    String content = s.toString().substring(0, 30);
                    set_profile_name.setText(content);
                    set_profile_name.setSelection(set_profile_name.getText().length());
                    Toasty.info(EditProfileActivity.this, getString(R.string.username_no_space), Toast.LENGTH_LONG).show();
                }
            }
        });


        set_change_header_picture.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                    PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(EditProfileActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_HEADER);
                return;
            }
            Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
            getIntent.setType("image/*");

            Intent pickIntent = new Intent(Intent.ACTION_PICK);
            pickIntent.setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

            Intent chooserIntent = Intent.createChooser(getIntent, getString(R.string.toot_select_image));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
            startActivityForResult(chooserIntent, PICK_IMAGE_HEADER);
        });

        set_change_profile_picture.setOnClickListener(v -> {

            if (ContextCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                    PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(EditProfileActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_PICTURE);
                return;
            }

            Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
            getIntent.setType("image/*");

            Intent pickIntent = new Intent(Intent.ACTION_PICK);
            pickIntent.setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

            Intent chooserIntent = Intent.createChooser(getIntent, getString(R.string.toot_select_image));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
            startActivityForResult(chooserIntent, PICK_IMAGE_PROFILE);
        });

        if (!EditProfileActivity.this.isFinishing()) {
            Glide.with(set_profile_picture.getContext())
                    .load(account.getAvatar())
                    .into(set_profile_picture);
            Glide.with(set_header_picture.getContext())
                    .load(account.getHeader())
                    .into(set_header_picture);
        }
        if (account.getHeader() == null || account.getHeader().contains("missing.png"))
            set_header_picture_overlay.setVisibility(View.VISIBLE);

        SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
        int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);

        set_profile_save.setOnClickListener(v -> {
            if (set_profile_name.getText() != null)
                profile_username = set_profile_name.getText().toString().trim();
            else
                profile_username = "";
            if (set_profile_description != null && set_profile_description.getHint() != null && set_profile_description.getText() != null && !set_profile_description.getText().toString().contentEquals(set_profile_description.getHint()))
                profile_note = set_profile_description.getText().toString().trim();
            else
                profile_note = null;
            int style;
            if (theme == Helper.THEME_DARK) {
                style = R.style.DialogDark;
            } else if (theme == Helper.THEME_BLACK) {
                style = R.style.DialogBlack;
            } else {
                style = R.style.Dialog;
            }
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(EditProfileActivity.this, style);
            LayoutInflater inflater = EditProfileActivity.this.getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.dialog_profile, new LinearLayout(EditProfileActivity.this), false);
            dialogBuilder.setView(dialogView);

            ImageView back_ground_image = dialogView.findViewById(R.id.back_ground_image);
            ImageView dialog_profile_picture = dialogView.findViewById(R.id.dialog_profile_picture);
            TextView dialog_profile_name = dialogView.findViewById(R.id.dialog_profile_name);
            TextView dialog_profile_description = dialogView.findViewById(R.id.dialog_profile_description);

            if (profile_username != null)
                dialog_profile_name.setText(profile_username);
            if (profile_note != null)
                dialog_profile_description.setText(profile_note);
            if (profile_header_bmp != null) {
                BitmapDrawable background = new BitmapDrawable(EditProfileActivity.this.getResources(), profile_header_bmp);
                back_ground_image.setBackground(background);
            } else {
                back_ground_image.setBackground(set_header_picture.getDrawable());
            }
            if (profile_picture_bmp != null) {
                BitmapDrawable background = new BitmapDrawable(EditProfileActivity.this.getResources(), profile_picture_bmp);
                dialog_profile_picture.setBackground(background);
            } else {
                dialog_profile_picture.setBackground(set_profile_picture.getDrawable());
            }
            profile_privacy = set_lock_account.isChecked() ? API.accountPrivacy.LOCKED : API.accountPrivacy.PUBLIC;
            sensitive = set_sensitive_content.isChecked();
            dialogBuilder.setPositiveButton(R.string.save, (dialog, id) -> {
                set_profile_save.setEnabled(false);
                new Thread(() -> Glide.get(EditProfileActivity.this).clearDiskCache()).start();
                Glide.get(EditProfileActivity.this).clearMemory();
                HashMap<String, String> newCustomFields = new HashMap<>();

                String key1, key2, key3, key4, val1, val2, val3, val4;
                key1 = ((EditText) findViewById(R.id.cf_key_1)).getText().toString();
                key2 = ((EditText) findViewById(R.id.cf_key_2)).getText().toString();
                key3 = ((EditText) findViewById(R.id.cf_key_3)).getText().toString();
                key4 = ((EditText) findViewById(R.id.cf_key_4)).getText().toString();

                val1 = ((EditText) findViewById(R.id.cf_val_1)).getText().toString();
                val2 = ((EditText) findViewById(R.id.cf_val_2)).getText().toString();
                val3 = ((EditText) findViewById(R.id.cf_val_3)).getText().toString();
                val4 = ((EditText) findViewById(R.id.cf_val_4)).getText().toString();

                newCustomFields.put(key1, val1);
                newCustomFields.put(key2, val2);
                newCustomFields.put(key3, val3);
                newCustomFields.put(key4, val4);

                new UpdateCredentialAsyncTask(EditProfileActivity.this, newCustomFields, profile_username, profile_note, profile_picture, avatarName, header_picture, headerName, profile_privacy, sensitive, EditProfileActivity.this).execute();
            });
            dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
            AlertDialog alertDialog = dialogBuilder.create();
            alertDialog.show();

        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_HEADER: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // We have the permission.
                    set_change_header_picture.callOnClick();
                }
                break;

            }
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_PICTURE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // We have the permission.
                    set_change_profile_picture.callOnClick();
                }
                break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_HEADER && resultCode == RESULT_OK) {
            if (data == null || data.getData() == null) {
                Toasty.error(EditProfileActivity.this, getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show();
                return;
            }
            Uri fileUri = data.getData();
            headerName = Helper.getFileName(EditProfileActivity.this, fileUri);
            try {
                InputStream inputStream = EditProfileActivity.this.getContentResolver().openInputStream(fileUri);
                assert inputStream != null;
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
                profile_header_bmp = ThumbnailUtils.extractThumbnail(bmp, 700, 335);
                set_header_picture.setImageBitmap(profile_header_bmp);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            header_picture = Helper.compressImage(EditProfileActivity.this, fileUri);
        } else if (requestCode == PICK_IMAGE_PROFILE && resultCode == RESULT_OK) {
            if (data == null || data.getData() == null) {
                Toasty.error(EditProfileActivity.this, getString(R.string.toot_select_image_error), Toast.LENGTH_LONG).show();
                return;
            }
            Uri fileUri = data.getData();
            avatarName = Helper.getFileName(EditProfileActivity.this, fileUri);
            try {
                InputStream inputStream = EditProfileActivity.this.getContentResolver().openInputStream(fileUri);
                assert inputStream != null;
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
                profile_picture_bmp = ThumbnailUtils.extractThumbnail(bmp, 400, 400);
                set_profile_picture.setImageBitmap(profile_picture_bmp);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            profile_picture = Helper.compressImage(EditProfileActivity.this, fileUri);
        }
    }

    @Override
    public void onUpdateCredential(APIResponse apiResponse) {
        set_profile_save.setEnabled(true);
        if (apiResponse.getError() != null) {
            Toasty.error(EditProfileActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
            return;
        }
        Toasty.success(EditProfileActivity.this, getString(R.string.toast_update_credential_ok), Toast.LENGTH_LONG).show();
        finish();
    }

}
