package de.beyondsoft.ownchat.page.profile;

import com.bumptech.glide.Glide;
import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.data.AppPrefsConstants;
import de.beyondsoft.ownchat.data.prefs.LongPreference;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.di.InjectionHelper;
import de.beyondsoft.ownchat.model.User;
import de.beyondsoft.ownchat.utils.DialogHandler;
import de.beyondsoft.ownchat.utils.FileUtils;
import de.beyondsoft.ownchat.utils.RuntimePermissionBaseFragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import javax.inject.Inject;
import javax.inject.Named;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import de.beyondsoft.ownchat.utils.ui.GlideApp;
import de.beyondsoft.ownchat.utils.ui.ViewUtils;

public class ProfileFragment extends RuntimePermissionBaseFragment implements ProfileView {

    private final static int SELECT_FILE = 5055;

    @BindView(R.id.profile_avatar)
    ImageView mAvatarImageview;

    @BindView(R.id.profile_name)
    TextView mNameTextView;

    @BindView(R.id.profile_phone_number)
    EditText mPhoneNumberEditText;

    @BindView(R.id.profile_change_button)
    Button mProfileChangeButton;

    @BindView(R.id.profile_update_button)
    Button mUpdateProfileButton;

    @BindView(R.id.profile_avatar_progress_bar)
    ProgressBar mProgressBar;

    @Inject
    @Named(AppPrefsConstants.NAME)
    StringPreference mProfileNamePreference;

    @Inject
    @Named(AppPrefsConstants.AVATAR)
    StringPreference mAvatarPreference;

    @Inject
    @Named(AppPrefsConstants.PHONE_NUMBER)
    StringPreference mPhoneNumberPreference;

    @Inject
    @Named(AppPrefsConstants.UPLOAD_MAX_SIZE)
    LongPreference mUploadMaxSizePreference;

    @Inject
    ProfilePresenter mProfilePresenter;

    private Callback mCallback;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        InjectionHelper.getProfileComponent(context).inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        getActivity().setTitle(R.string.title_profile);

        GlideApp.with(getActivity())
                .load(mAvatarPreference.get())
                .placeholder(R.drawable.avatar)
                .into(mAvatarImageview);

        ViewUtils.setProgressBarColor(mProgressBar, R.color.colorDefault);

        if(!TextUtils.isEmpty(mPhoneNumberPreference.get())) {
            mPhoneNumberEditText.setText(mPhoneNumberPreference.get());
        }

        if(!TextUtils.isEmpty(mProfileNamePreference.get())) {
            mNameTextView.setText(mProfileNamePreference.get());
        }

        mProfilePresenter.attachView(this);
        mCallback.getProfile();
    }

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

        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        if (null == data) {
            return;
        }

        if (requestCode == SELECT_FILE) {
            if (null == data.getData()) {
                return;
            }

            final Uri uri = data.getData();

            if (Build.VERSION.SDK_INT >= 19) {
                final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // Check for the freshest data.
                try {
                    //noinspection WrongConstant
                    getActivity().getContentResolver().takePersistableUriPermission(uri, takeFlags);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!mProfilePresenter.isAttached()) {
                mProfilePresenter.attachView(this);
            }

            mProgressBar.setVisibility(View.VISIBLE);

            File file = new File(uri.getPath());

            if(mUploadMaxSizePreference.get() > 0 && file.length() > mUploadMaxSizePreference.get()) {
                mProgressBar.setVisibility(View.GONE);
                showError(R.string.error_file_is_too_large);
                return;
            }

            mCallback.uploadImage(uri);
        }
    }

    @Override
    public File getFile(Uri uri) {
        return FileUtils.getFile(getActivity(), uri);
    }

    @Override
    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    @Override
    public void setProfile(User user) {
        if (!TextUtils.isEmpty(user.avatar)) {
            Glide.with(getActivity()).load(user.avatar).into(mAvatarImageview);
        }

        mProfileChangeButton.setEnabled(true);
        mNameTextView.setText(user.firstName.concat(" ").concat(user.lastName));
        mPhoneNumberEditText.setText(user.mobile);
        mAvatarPreference.set(user.avatar);
        mProfileNamePreference.set(user.firstName.concat(" ").concat(user.lastName));
        mPhoneNumberPreference.set(user.mobile);
    }

    @Override
    public void showError(@StringRes int message) {
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void refreshImage(String imageUrl) {
        mProgressBar.setVisibility(View.GONE);

        GlideApp.with(getContext())
                .load(imageUrl)
                .error(R.drawable.avatar)
                .into(mAvatarImageview);

        mAvatarPreference.set(imageUrl);
    }

    @OnClick(R.id.profile_change_button)
    public void onChangeAvatar() {
        requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, MY_STORAGE_PERMISSION);
    }

    public void choosePicture() {
        selectFile();
    }

    @OnClick(R.id.profile_update_button)
    public void onProfileUpdate() {
        mProfileChangeButton.setEnabled(false);
        mCallback.updateProfile(mPhoneNumberEditText.getText().toString());
    }

    @Override
    public void onPermissionGranted(int permissionCode) {
        if (MY_STORAGE_PERMISSION == permissionCode) {
            choosePicture();
        }
    }

    @OnTextChanged(value = R.id.profile_phone_number, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void phoneNumberChanged() {
        mUpdateProfileButton.setEnabled(!TextUtils.isEmpty(mPhoneNumberEditText.getText().toString()) && mPhoneNumberEditText.getText().toString().trim().length() > 0);
    }

    @Override
    public void onPermissionDenied(int permissionCode) {
        if (MY_STORAGE_PERMISSION == permissionCode) {
            DialogHandler.showSimpleDialog(getActivity(),
                    R.string.error,
                    R.string.change_avatar_permisssion,
                    android.R.string.ok,
                    null).show();
        }
    }

    private void selectFile() {
        Intent intent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        } else {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
        }

        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.chat_select_file)), SELECT_FILE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mProfilePresenter.detachView();
    }
}
