package com.hikapro.backpack.presenter;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.view.View;

import org.brickred.socialauth.Profile;
import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthError;
import org.brickred.socialauth.android.SocialAuthListener;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by tariel on 16/05/16.
 */
public class SharePresenter implements Presenter.Share {

    private ShareDialog shareDialog;
    private CallbackManager callbackManager;

    private Button facebookButton;
    private Button twitterButton;
    private Button cancelButton;
    private ImageView sharingImage;

    private TextView twitterLogin;
    private Profile twitterProfile;
    private ViewGroup progress;
    private boolean canPost;
    private boolean showError;

    protected SocialAuthAdapter socialAuthAdapter;

    private WeakReference<View.Share>   view;
    private Model.Share                 model;

    @Override
    public Context getAppContext() {
        try {
            return getView().getAppContext();
        } catch (NullPointerException e) {
            return null;
        }
    }

    @Override
    public Context getActivityContext() {
        try {
            return getView().getActivityContext();
        } catch (NullPointerException e) {
            return null;
        }
    }

    @Override
    public void setView(View.Share view) {
        this.view = new WeakReference<>(view);

    }

    @Override
    public void setModel(Model.Share model) {
        this.model = model;
    }

    @Override
    public void notifyDataSetChanged() {
        Bitmap [] pics = model.getSharingPics();
        if (pics != null && pics[1] != null && pics[0] != null) {
            canPost = true;
            sharingImage.setImageBitmap(pics[0]);
        } else {
            showError = true;
            canPost = true;
        }
        setVisibility();
    }

    @Override
    public Model.Share getModel() {
        return model;
    }

    @Override
    public void onDestroy(boolean isChangingConfiguration) {
        view = null;
        model.onDestroy(isChangingConfiguration);
        if ( !isChangingConfiguration ) {
            model = null;
        }
    }

    @Override
    public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
                                          Bundle savedInstanceState) {
        android.view.View v = inflater.inflate(R.layout.fragment_share, container, false);

        FacebookSdk.sdkInitialize(getAppContext());
        //AppEventsLogger.activateApp(getActivityContext());
        callbackManager = CallbackManager.Factory.create();
        shareDialog = new ShareDialog((Activity) getActivityContext());
        facebookButton = (Button) v.findViewById(R.id.facebook_share_button);
        twitterButton = (Button) v.findViewById(R.id.twitter_share_button);
        progress = (ViewGroup) v.findViewById(R.id.share_progress_container);

        sharingImage = (ImageView) v.findViewById(R.id.share_image_view);
        model.executeQuery();
        shareDialog.registerCallback(callbackManager, new

                FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        Toast.makeText(getActivityContext(), R.string.fb_posted,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel() {}

                    @Override
                    public void onError(FacebookException error) {
                        Toast.makeText(getActivityContext(), R.string.fb_error,
                                Toast.LENGTH_SHORT).show();
                        Log.e("Share", "Facebook error", error);
                    }
                });
        facebookButton.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                if (ShareDialog.canShow(ShareLinkContent.class)) {

                    try {
                        Context context  = getAppContext();

                        ShareLinkContent linkContent = new ShareLinkContent.Builder()
                                .setContentTitle(context.getString(R.string.facebook_sharing_header))
                                .setContentDescription(context.getString(R.string.facebook_sharing_txt))
                                .setContentUrl(Uri.parse(context.getString(R.string.facebook_url)))

                                .setShareHashtag(new ShareHashtag.Builder()
                                        .setHashtag("#PackWithMe")
                                        .build())
                                .build();

                        shareDialog.show(linkContent);

                    } catch (Exception e) {
                        Toast.makeText(getActivityContext(), R.string.fb_error,
                                Toast.LENGTH_SHORT).show();
                        Log.e("Sharing", "Facebook error", e);
                    }
                }
            }
        });

        twitterButton.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                if (! canPost )
                    Toast.makeText(getActivityContext(), R.string.please_wait, Toast.LENGTH_SHORT).show();
                else if (showError)
                    Toast.makeText(getActivityContext(), R.string.cannot_post, Toast.LENGTH_SHORT).show();
                else
                    postToTwitter();
            }
        });

        Activity activity = (Activity) getActivityContext();
        if (activity != null) {
            ActionBar actionBar = activity.getActionBar();
            if (actionBar != null) {
                ViewGroup custActionBarView = (ViewGroup) inflater.inflate(R.layout.share_cust_actionbar, null);
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setDisplayShowCustomEnabled(true);
                actionBar.setDisplayHomeAsUpEnabled(false);
                actionBar.setCustomView(custActionBarView);

                cancelButton    = (Button) custActionBarView.findViewById(R.id.action_share_cancel);
                cancelButton.setOnClickListener(new android.view.View.OnClickListener() {
                    @Override
                    public void onClick(android.view.View v) {
                        Fragment fragment = (Fragment) getView();
                        if (fragment != null)
                            fragment.getFragmentManager().popBackStack();

                    }
                });
            }
        }
        twitterLogin = (TextView) v.findViewById(R.id.twitter_login);
        setVisibility();
        return v;
    }

    private View.Share getView() throws NullPointerException {
        if ( view != null )
            return view.get();
        else
            throw new NullPointerException("View is unavailable");
    }



    private class ResponseListener implements DialogListener {
        Bitmap bitmap;
        String message;

        public ResponseListener(Bitmap bitmap, String message) {
            this.bitmap = bitmap;
            this.message = message;
        }
        @Override
        public void onComplete(final Bundle values) {
            try {
                socialAuthAdapter.getUserProfileAsync(new ProfileDataListener());
                socialAuthAdapter.uploadImageAsync(message, "PackWithMe.png",
                        bitmap, 0, new UploadImageListener());
            } catch (Exception e) {
                Log.e("ShareTwitter", e.getMessage());
            }
        }
        @Override
        public void onError(SocialAuthError error) {
            Log.d("ShareTwitter", "Authentication Error: " + error.getMessage());
        }

        @Override
        public void onCancel() {
            Log.d("ShareTwitter", "Authentication Cancelled");
        }

        @Override
        public void onBack() {
            Log.d("ShareTwitter", "Dialog Closed by pressing Back Key");
        }
    }

    private final class UploadImageListener implements SocialAuthListener {
        @Override
        public void onExecute(String s, Object o) {
            Integer status = (Integer) o;
            try {
                if (status.intValue() == 200 || status.intValue() == 201
                        || status.intValue() == 204) {
                    Toast.makeText(getActivityContext(), R.string.twitter_posted,
                            Toast.LENGTH_SHORT).show();
                    Log.d("ShareTwitter", "Posting completed");
                } else {
                    Toast.makeText(getActivityContext(), R.string.twitter_error2,
                            Toast.LENGTH_SHORT).show();
                    Log.d("ShareTwitter", "Posting failed");
                }
            } catch (NullPointerException e) {
                Toast.makeText(getActivityContext(), R.string.twitter_error2,
                        Toast.LENGTH_SHORT).show();
                Log.e("ShareTwitter", e.getMessage());
            }
        }

        @Override
        public void onError(SocialAuthError e) {
            Toast.makeText(getActivityContext(), "Posting to twitter failed!",
                    Toast.LENGTH_SHORT).show();
            Log.e("ShareTwitter", e.getMessage());
        }

    }

    private final class ProfileDataListener implements SocialAuthListener<Profile> {


        @Override
        public void onExecute(String s, Profile profile) {
            twitterProfile = profile;
            if (twitterProfile != null && twitterLogin != null) {
                twitterLogin.setText(twitterProfile.getDisplayName());
            }
        }


        @Override
        public void onError(SocialAuthError socialAuthError) {

        }
    }

    private void setVisibility() {
        if (showError) {
            progress.setVisibility(android.view.View.GONE);
            sharingImage.setVisibility(android.view.View.VISIBLE);
        }
        else {
            progress.setVisibility(canPost ? android.view.View.GONE : android.view.View.VISIBLE);
            sharingImage.setVisibility(canPost ? android.view.View.VISIBLE : android.view.View.GONE);
        }

    }

    private void postToTwitter() {
        final Dialog dialog = new Dialog(getActivityContext());

        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_twitter);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        Button cancel = (Button) dialog.findViewById(R.id.button_cancel);
        Button post = (Button) dialog.findViewById(R.id.button_post);
        final EditText editText = (EditText) dialog.findViewById(R.id.message);
        final ImageView imageView = (ImageView) dialog.findViewById(R.id.image_to_post);
        final TextView textView = (TextView) dialog.findViewById(R.id.chars_left);

        textView.setText(String.valueOf(140 - editText.getText().length()));

        if (model.getSharingPics() != null) {
            Bitmap sharingBitmap = model.getSharingPics()[1];
            if (sharingBitmap != null) {
                imageView.setImageBitmap(sharingBitmap);
            } else {
                Toast.makeText(getActivityContext(), R.string.twitter_error, Toast.LENGTH_SHORT).show();
            }

        }

        editText.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) {
                int left = 140 - s.length();
                textView.setText(String.valueOf(left));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        cancel.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                try {
                    dialog.dismiss();
                } catch (Exception e) {

                }
            }
        });

        post.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {

                socialAuthAdapter = new SocialAuthAdapter(new ResponseListener(((BitmapDrawable)imageView.getDrawable()).getBitmap(),
                        editText.getText().toString()));
                socialAuthAdapter.addProvider(SocialAuthAdapter.Provider.TWITTER, R.drawable.ic_twitter_icon);
                socialAuthAdapter.authorize(getActivityContext(), SocialAuthAdapter.Provider.TWITTER);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    }
