package com.p3.bewoplaner.page.profile;

import com.bumptech.glide.Glide;
import com.p3.bewoplaner.R;
import com.p3.bewoplaner.data.AppPrefsConstants;
import com.p3.bewoplaner.data.prefs.StringPreference;
import com.p3.bewoplaner.di.InjectionHelper;
import com.p3.bewoplaner.model.User;
import com.p3.bewoplaner.utils.DialogHandler;
import com.p3.bewoplaner.utils.FileUtils;
import com.p3.bewoplaner.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.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.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by imarneanu on 2/13/17.
 */
public class ProfileFragment extends RuntimePermissionBaseFragment implements ProfileView {

    private final static int SELECT_FILE = 5055;

    @BindView(R.id.profile_avatar)
    CircleImageView 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;

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

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

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

    @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);
        Glide.with(getActivity())
                .load(mAvatarPreference.get())
                .into(mAvatarImageview);

        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 {
                    getActivity().getContentResolver().takePersistableUriPermission(uri, takeFlags);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (!mProfilePresenter.isAttached()) {
                mProfilePresenter.attachView(this);
            }
            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) {
        Glide.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();
    }
}
