package org.schabi.newpipe.settings;

import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
import org.schabi.newpipe.R;
import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper;
import org.schabi.newpipe.views.YouTubeLoginWebViewActivity;

public class YouTubeAccountSettingsFragment extends BaseAccountSettingsFragment {

    @Override
    protected int getPreferenceResource() {
        return R.xml.account_settings_youtube;
    }

    @Override
    protected Class<?> getLoginActivityClass() {
        return YouTubeLoginWebViewActivity.class;
    }

    @Override
    protected String getCookiesKey() {
        return getString(R.string.youtube_cookies_key);
    }

    @Override
    protected String getOverrideSwitchKey() {
        return getString(R.string.override_cookies_youtube_key);
    }

    @Override
    protected String getOverrideValueKey() {
        return getString(R.string.override_cookies_youtube_value_key);
    }

    @Override
    protected boolean shouldCheckOverrideKeys() {
        return false; // YouTube doesn't use override preferences
    }

    @Override
    protected void handleLoginResult(Intent data) {
        String cookies = data.getStringExtra("cookies");
        String pot = data.getStringExtra("pot");

        defaultPreferences.edit().putString(getCookiesKey(), cookies).apply();
        defaultPreferences.edit().putString(getString(R.string.youtube_po_token_key), pot).apply();

        try {
            YoutubeParsingHelper.getAuthorizationHeader(cookies);
            onLoginSuccess();
        } catch (Exception e) {
            Toast.makeText(requireContext(), R.string.try_again, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void performLogout() {
        defaultPreferences.edit().putString(getCookiesKey(), "").apply();
        defaultPreferences.edit().putString(getString(R.string.youtube_po_token_key), "").apply();
        onLogoutSuccess();
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
}
