package org.deke.risk.riskahead.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterConfig;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;

import org.deke.risk.riskahead.LoginActivity;
import org.deke.risk.riskahead.R;

/**
 *
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 *
 */
public class TwitterButtonFragment extends Fragment {
    private final static String TAG = ProfileStatisticsFragment.class.getSimpleName();

    private BootstrapButton btnLoginTW;
    private TwitterAuthClient client;
    TwitterSession session = null;
    Context mContext;
    View view;

    // Note: Your consumer key and secret should be obfuscated in your source code before shipping.
    private static final String TWITTER_KEY = "t8o7YBmzj3JMRf6RjIBg7hF20";
    private static final String TWITTER_SECRET = "HTt4mOqyDStslzq1RXHUqU6HcZpOuSuzC2iWH45MlUsZBRI704";

    public TwitterButtonFragment() {
        // Required empty public constructor
    }

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try{
            Activity mActivity = getActivity();
            assert mActivity != null;
            mContext = mActivity.getApplicationContext();
        }catch(Exception e){
            FirebaseCrashlytics.getInstance().log("Could not get activity for TwitterButton");
            FirebaseCrashlytics.getInstance().recordException(e);
        }

        TwitterConfig config = new TwitterConfig.Builder(mContext)
                .logger(new DefaultLogger(Log.INFO))
                .twitterAuthConfig(new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET))
                .debug(true)
                .build();
        Twitter.initialize(config);
        client = new TwitterAuthClient();

        view = inflater.inflate(R.layout.fragment_twitter_button, container, false);
        btnLoginTW = view.findViewById(R.id.btn_login_twitter);

        btnLoginTW.setOnClickListener((View v) ->
                client.authorize(getActivity(), new Callback<TwitterSession>() {
                    @Override
                    public void success(Result<TwitterSession> result) {
                        Log.e("Debug", "onSuccess wird ausgeführt");
                        session = result.data;
                        ((LoginActivity) getActivity()).handleSocialMediaLogin((Long.toString(session.getUserId())), "twitter", session.getUserName(), "");
                    }

                    @Override
                    public void failure(TwitterException exception) {
                        FirebaseCrashlytics.getInstance().log("onFailure wird ausgeführt: "+exception);
                        showMessage("Could not log in with Twitter. Please use E-Mail instead or try again later.");
                    }
                })
        );

        return view;
    }

    private void setUpSignOut() {
        btnLoginTW.setOnClickListener(v -> {
            TwitterCore.getInstance().getSessionManager().clearActiveSession();

            Toast.makeText(mContext, "All accounts are cleared",Toast.LENGTH_SHORT).show();
        });
    }

    private boolean isAuthed() {
        final TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
        return session != null && session.getAuthToken() != null;
    }

    public void showMessage(String statusText){
        Toast.makeText(mContext,statusText,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        client.onActivityResult(requestCode, resultCode, data);
    }

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

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

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

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

}
