package com.zouag.contacts.screens.viewcontact;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;

import com.zouag.contacts.R;
import com.zouag.contacts.data.ContactRepository;
import com.zouag.contacts.data.models.Contact;
import com.zouag.contacts.data.models.ContactData;
import com.zouag.contacts.screens.altercontact.AlterContactActivity;
import com.zouag.contacts.utils.ResultCodes;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;

public class ViewContactPresenter implements ViewContactContract.Presenter {


    private SharedPreferences sharedPref;
    private Context mContext;
    /**
     * A list of this contact's data. (Phone + Email + Address)
     */
    private List<ContactData> contactDataList;

    /**
     * The currently viewed contact.
     */
    private Contact currentContact;
    private ContactRepository mContactRepository;
    private ViewContactContract.View mView;
    private CompositeDisposable mCompositeDisposable;

    @Inject
    public ViewContactPresenter(ContactRepository contactRepository, ViewContactContract.View view) {
        this.mView = view;
        mContext = mView.getContext();
        mContactRepository = contactRepository;
        sharedPref = PreferenceManager.getDefaultSharedPreferences(mContext);
        mCompositeDisposable = new CompositeDisposable();
    }

    @Override
    public void loadCurrentContact(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // Get saved contact from previous orientation change
            currentContact = savedInstanceState.getParcelable("savedContact");
        } else {
            // Get contact from launching intent
            currentContact = mView.getIntent().getExtras().getParcelable("contact");
        }
        mView.setActionbarTitle(currentContact.getName());
    }

    @Override
    public void loadContactData() {
        String imgPath = currentContact.getImgPath();
        if ("".equals(imgPath))
            mView.setProfileImage(R.drawable.ic_action_user);
        else
            mView.setProfileImage(Uri.fromFile(new File(imgPath)));

        if (contactDataList == null)
            contactDataList = new ArrayList<>();
        else
            contactDataList.clear();

        if (!"".equals(currentContact.getPhoneNumber())) {
            contactDataList.add(
                    new ContactData(
                            mContext.getString(R.string.mobile),
                            currentContact.getPhoneNumber(),
                            R.drawable.ic_action_phone_start));
        }

        if (!"".equals(currentContact.getEmail())) {
            contactDataList.add(
                    new ContactData(
                            mContext.getString(R.string.email),
                            currentContact.getEmail(),
                            R.drawable.ic_action_attachment));
        }

        if (!"".equals(currentContact.getAddress())) {
            contactDataList.add(
                    new ContactData(
                            mContext.getString(R.string.address),
                            currentContact.getAddress(),
                            R.drawable.ic_action_location));
        }

        mView.displayContactData(contactDataList);
    }

    @Override
    public void requestNewContactInfo() {
        mCompositeDisposable.add(
                mContactRepository.getById(currentContact.getId())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(contact -> {
                            currentContact = contact;
                            loadContactData();
                            mView.setActionbarTitle(currentContact.getName());
                            mView.displayContactData(contactDataList);
                        })
        );
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable("savedContact", currentContact);
    }

    /**
     * Deletes a contact from the local database.
     */
    @Override
    public void deleteContact() {
        // Get the setting
        boolean confirm_delete = sharedPref.getBoolean(
                mContext.getString(R.string.show_confirm_dialog), true);

        if (!confirm_delete) {
            // Delete contact without prompting a confirmation dialog
            performDeletion();
        } else
            mView.showDeleteDialog();
    }

    @Override
    public void performDeletion() {
        mContactRepository.delete(currentContact);

        Intent intent = new Intent();
        intent.putExtra("deletedContact", currentContact);
        mView.setResult(ResultCodes.CONTACT_DELETED, intent);
        mView.finish();
    }

    @Override
    public void updateContact() {
        Intent intent = new Intent(mContext, AlterContactActivity.class);
        intent.putExtra("isUpdating", true);
        intent.putExtra("contact", currentContact);
        mView.navigateToUpdateContactActivity(intent);
    }

    @Override
    public void unsubscribe() {
        mCompositeDisposable.clear();
    }

    @Override
    public void start(Bundle savedInstanceState) {
        loadCurrentContact(savedInstanceState);
        loadContactData();
    }
}
