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.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
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.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.AccountData.Account;
import app.fedilab.fedilabtube.drawer.OwnAccountsAdapter;
import app.fedilab.fedilabtube.fragment.DisplayAccountsFragment;
import app.fedilab.fedilabtube.fragment.DisplayChannelsFragment;
import app.fedilab.fedilabtube.fragment.DisplayNotificationsFragment;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.sqlite.AccountDAO;
import app.fedilab.fedilabtube.sqlite.Sqlite;


public class AccountActivity extends AppCompatActivity {


    private ViewPager mPager;
    private TabLayout tabLayout;

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


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


        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(AccountActivity.this, Helper.getColorAccent())), 0, content_create.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
        SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
        String token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null);

        TextView instanceView = findViewById(R.id.instance);
        Account account = new AccountDAO(AccountActivity.this, db).getAccountByToken(token);

        if (account == null) {
            Helper.logoutCurrentUser(AccountActivity.this, null);
            return;
        }

        ImageView profile_picture = findViewById(R.id.profile_picture);
        TextView username = findViewById(R.id.username);
        TextView displayname = findViewById(R.id.displayname);

        setTitle(String.format("@%s", account.getUsername()));

        Helper.loadGiF(AccountActivity.this, account.getAvatar().getPath(), profile_picture);
        username.setText(String.format("@%s", account.getUsername()));
        displayname.setText(account.getDisplayName());

        instanceView.setText(account.getHost());

        Button logout_button = findViewById(R.id.logout_button);
        logout_button.setOnClickListener(v -> {
            AlertDialog.Builder dialogBuilderLogoutAccount = new AlertDialog.Builder(AccountActivity.this);
            dialogBuilderLogoutAccount.setMessage(getString(R.string.logout_account_confirmation, account.getUsername(), account.getHost()));
            dialogBuilderLogoutAccount.setPositiveButton(R.string.action_logout, (dialog, id) -> {
                Helper.logoutCurrentUser(AccountActivity.this, account);
                dialog.dismiss();
            });
            dialogBuilderLogoutAccount.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());
            AlertDialog alertDialogLogoutAccount = dialogBuilderLogoutAccount.create();
            alertDialogLogoutAccount.show();
        });

        Button settings = findViewById(R.id.settings);
        settings.setOnClickListener(v -> {
            Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
            startActivity(intent);
        });

        tabLayout = findViewById(R.id.account_tabLayout);
        mPager = findViewById(R.id.account_viewpager);
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_notifications)));
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_muted)));
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_channel)));


        mPager.setOffscreenPageLimit(3);


        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                TabLayout.Tab tab = tabLayout.getTabAt(position);
                if (tab != null)
                    tab.select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                Fragment fragment = null;
                if (mPager.getAdapter() != null)
                    fragment = (Fragment) mPager.getAdapter().instantiateItem(mPager, tab.getPosition());
                switch (tab.getPosition()) {
                    case 0:
                        if (fragment != null) {
                            DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment);
                            displayNotificationsFragment.scrollToTop();
                        }
                        break;
                    case 1:
                        if (fragment != null) {
                            DisplayAccountsFragment displayAccountsFragment = ((DisplayAccountsFragment) fragment);
                            displayAccountsFragment.scrollToTop();
                        }
                        break;
                    case 2:
                        if (fragment != null) {
                            DisplayChannelsFragment displayChannelsFragment = ((DisplayChannelsFragment) fragment);
                            displayChannelsFragment.scrollToTop();
                        }
                        break;
                }
            }
        });

        PagerAdapter mPagerAdapter = new AccountsPagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);

    }

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

    @Override
    public boolean onCreateOptionsMenu(@NotNull Menu menu) {
        getMenuInflater().inflate(R.menu.main_profile, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        } else if (item.getItemId() == R.id.action_add_account) {
            SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
            List<Account> accounts = new AccountDAO(AccountActivity.this, db).getAllAccount();

            AlertDialog.Builder builderSingle = new AlertDialog.Builder(AccountActivity.this);
            builderSingle.setTitle(getString(R.string.list_of_accounts));
            if (accounts != null) {
                final OwnAccountsAdapter accountsListAdapter = new OwnAccountsAdapter(AccountActivity.this, accounts);
                final Account[] accountArray = new Account[accounts.size()];
                int i = 0;
                for (Account account : accounts) {
                    accountArray[i] = account;
                    i++;
                }
                builderSingle.setAdapter(accountsListAdapter, (dialog, which) -> {
                    final Account account = accountArray[which];
                    SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, account.getToken());
                    editor.putString(Helper.PREF_INSTANCE, account.getHost());
                    editor.putString(Helper.PREF_KEY_ID, account.getId());
                    editor.putString(Helper.PREF_KEY_NAME, account.getUsername());
                    editor.apply();
                    dialog.dismiss();
                    Intent intent = new Intent(AccountActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                });
            }
            builderSingle.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
            builderSingle.setPositiveButton(R.string.add_account, (dialog, which) -> {
                Intent intent = new Intent(AccountActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            });

            builderSingle.show();
        }
        return super.onOptionsItemSelected(item);
    }

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


    /**
     * Pager adapter for three tabs (notifications, muted, blocked)
     */
    private static class AccountsPagerAdapter extends FragmentStatePagerAdapter {

        AccountsPagerAdapter(FragmentManager fm) {
            super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        @NotNull
        @Override
        public Fragment getItem(int position) {
            Bundle bundle = new Bundle();
            switch (position) {
                case 1:
                    DisplayAccountsFragment displayAccountsFragment = new DisplayAccountsFragment();
                    bundle.putSerializable("accountFetch", RetrofitPeertubeAPI.DataType.MUTED);
                    displayAccountsFragment.setArguments(bundle);
                    return displayAccountsFragment;
                case 2:
                    return new DisplayChannelsFragment();
                default:
                    return new DisplayNotificationsFragment();
            }
        }

        @Override
        public int getCount() {
            return 3;
        }
    }


}