package de.beyondsoft.ownchat.page.sharing;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.data.AppPrefsConstants;
import de.beyondsoft.ownchat.data.prefs.BooleanPreference;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.di.InjectionHelper;
import de.beyondsoft.ownchat.model.Group;
import de.beyondsoft.ownchat.page.chat.GroupChatActivity;
import de.beyondsoft.ownchat.page.chat.SingleChatActivity;
import de.beyondsoft.ownchat.page.common.RuntimePermissionActivity;
import de.beyondsoft.ownchat.page.login.LoginActivity;
import de.beyondsoft.ownchat.page.main.MainActivity;
import de.beyondsoft.ownchat.utils.Constants;
import de.beyondsoft.ownchat.utils.ui.EmptyLayout;
import de.beyondsoft.ownchat.utils.ui.HorizontalDividerItemDecoration;

public class SharingActivity extends RuntimePermissionActivity implements SharingView, SharingContactsAdapter.OnOpenClickListener {
    private static String LOG_TAG = "SHARING_ACTIVITY";

    @Inject
    SharingPresenter mSharingPresenter;

    @Inject
    @Named(AppPrefsConstants.LOGIN_TOKEN)
    StringPreference mLoginTokenPreference;

    @BindView(R.id.sharing_contacts_recycler_view)
    RecyclerView mContactsRecyclerView;

    @BindView(R.id.sharing_contacts_coordinator_layout)
    CoordinatorLayout mCoordinatorLayout;

    @BindView(R.id.sharing_contacts_empty_layout)
    EmptyLayout mEmptyLayout;

    @BindView(R.id.chat_toolbar_single_title)
    TextView mSingleChatTitleTextView;

    @Inject
    @Named(AppPrefsConstants.PATH_TO_FILE_TO_SHARE)
    StringPreference mSelectedFilePath;

    @Inject
    @Named(AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY)
    BooleanPreference mIsComingFromSharingActivity;

    @Inject
    @Named(AppPrefsConstants.IS_FILE)
    BooleanPreference mIsFile;

    private SharingView.Callback mCallback;
    private SharingContactsAdapter mContactsAdapter;
    private Snackbar mSnackbar;
    private Intent mIntent;

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

        setContentView(R.layout.activity_sharing);

        InjectionHelper.getSharingComponent(this).inject(this);
        ButterKnife.bind(this);

        mSharingPresenter.attachView(this);

        setToolBar();

        mIntent = getIntent();

        requestAppPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, R.string.permission_storage_explained, 777, this::shareFile);
    }

    private void returnToContactList(int requestCode) {
        mSelectedFilePath.delete();
        mIsComingFromSharingActivity.set(false);
        startActivity(new Intent(this, MainActivity.class));
        finishAffinity();
    }

    private void shareFile(int requestCode) {
        mContactsRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).colorResId(R.color.colorFill).build());
        mContactsRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mContactsAdapter = new SharingContactsAdapter(this);
        mContactsRecyclerView.setAdapter(mContactsAdapter);

        String action = mIntent.getAction();
        String type = mIntent.getType();

        Log.i(LOG_TAG, "action equals ACTION_SEND: " + Intent.ACTION_SEND.equals(action) + "; type: " + type);

        if(Intent.ACTION_SEND.equals(action) && type != null) {
            if("text/plain".equals(type)) {
                handleSendText(mIntent);
            } else if(type.startsWith("image/") || type.startsWith("video") || type.startsWith("audio")) {
                handleSendFile(mIntent);
            }
        }
    }

    void handleSendFile(Intent intent) {
        Uri fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);

        if(fileUri != null) {
            mSelectedFilePath.set(fileUri.toString());
            mIsComingFromSharingActivity.set(true);
            mIsFile.set(true);

            if(!mLoginTokenPreference.isSet()) {
                startActivity(new Intent(this, LoginActivity.class));
                finishAffinity();
            }
        }
    }

    void handleSendText(Intent intent) {
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);

        if(sharedText != null) {
            mSelectedFilePath.set(sharedText);
            mIsComingFromSharingActivity.set(true);
            mIsFile.set(false);

            if(!mLoginTokenPreference.isSet()) {
                startActivity(new Intent(this, LoginActivity.class));
                finishAffinity();
            }
        }
    }

    private void setToolBar() {
        mSingleChatTitleTextView.setVisibility(View.VISIBLE);
        mSingleChatTitleTextView.setText(R.string.sharing_title);
    }

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

    @Override
    public void showError(@StringRes int message) {
        if(mSnackbar == null) {
            mSnackbar = Snackbar.make(mCoordinatorLayout, message, Snackbar.LENGTH_LONG);
            mSnackbar.setActionTextColor(ContextCompat.getColor(this, R.color.colorDefault));
        }

        mSnackbar.setText(message);
        mSnackbar.show();
    }

    @Override
    public void onOpenGroupMessage(Group group) {
        Intent intent = GroupChatActivity.createIntent(this, group);
        intent.putExtra(Constants.HAS_OPEN_CHAT, true);

        startActivity(intent);
        finishAffinity();
    }

    @Override
    public void onOpenPrivateMessage(Group contact) {
        Intent intent = SingleChatActivity.createIntent(this, contact);

        intent.putExtra(Constants.HAS_OPEN_CHAT, true);

        startActivity(intent);
        finishAffinity();
    }

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

    @Override
    public void showProgress() {
        mEmptyLayout.showLoading();
    }

    @Override
    public void hideProgress() {
        mEmptyLayout.setVisibility(View.GONE);
    }

    @Override
    public void setGroups(ArrayList<Group> groups) {
        mContactsAdapter.setGroups(groups);
    }

    @OnClick(R.id.chat_toolbar_back_arrow)
    public void onBackArrowClick(View view) {
        returnToContactList(0);
    }
}
