package co.pixelbeard.theanfieldwrap.devices;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import org.parceler.Parcels;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.Device;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.local.LocalRepository;
import co.pixelbeard.theanfieldwrap.data.source.remote.RemoteRepository;
import co.pixelbeard.theanfieldwrap.dialog.LoadingDialog;
import co.pixelbeard.theanfieldwrap.dialog.twoButton.TwoButtonDialogListener;
import co.pixelbeard.theanfieldwrap.utils.ActivityRequestCodes;
import co.pixelbeard.theanfieldwrap.utils.AnimUtils;
import co.pixelbeard.theanfieldwrap.utils.BaseActivity;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.DialogUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import co.pixelbeard.theanfieldwrap.walkthrough.WalkthroughActivity;
import io.realm.Realm;

public class DevicesActivity extends BaseActivity implements DevicesContract.View {

    private static final String TAG = DevicesActivity.class.getSimpleName();

    @BindView(R.id.ll_back)
    LinearLayout llBack;

    @BindView(R.id.srl_devices)
    SwipeRefreshLayout srlDevices;
    @BindView(R.id.txt_devices_title)
    TextView txtDevicesTitle;
    @BindView(R.id.rv_devices)
    RecyclerView rvDevices;

    @BindView(R.id.ll_no_internet_header)
    LinearLayout llNoInternetHeader;

    @BindView(R.id.txt_no_internet_header)
    TextView txtNoInternetHeader;

    private List<Device> mDevices;
    private LoadingDialog loadingDialog;

    private DevicesAdapter devicesAdapter;

    private DevicesContract.Presenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devices);

        ButterKnife.bind(this);

        new DevicesPresenter(this, new DataRepository(new LocalRepository(Realm.getDefaultInstance()), new RemoteRepository()));

        setTextViewFonts();
        setClickListener();
        setLayoutManager();
        setSwipeRefreshListener();

        mDevices = Parcels.unwrap(getIntent().getParcelableExtra("DEVICES"));

        if (mDevices != null) {
            srlDevices.setEnabled(false);
        }

        new Handler().postDelayed(() -> {
            if (mDevices == null || mDevices.size() == 0) {
                showLoader("Loading");
            }
            mPresenter.getDevices(mDevices);

        }, 300);

    }

    @Override
    protected void onResume() {
        super.onResume();
        TawController.setCurrentPage(TAG);
    }

    private void setTextViewFonts() {
        txtDevicesTitle.setTypeface(FontUtils.getInstance().getDinProBlack());
        txtNoInternetHeader.setTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setClickListener() {
        llBack.setOnClickListener(v -> finishDevicesActivityWithNoResult());
    }

    private void setLayoutManager() {
        rvDevices.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
    }

    private void setSwipeRefreshListener() {
        srlDevices.setOnRefreshListener(() -> mPresenter.getDevices(mDevices));
    }

    @Override
    public void setPresenter(DevicesContract.Presenter presenter) {
        if (presenter != null) {
            this.mPresenter = presenter;
        } else {
            throw new RuntimeException("Presenter is null");
        }
    }

    @Override
    public void goBack() {
        onBackPressed();
    }

    @Override
    public void showLoader(String text) {
        loadingDialog = new LoadingDialog(text, this);
        loadingDialog.setCancelable(false);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
    }

    @Override
    public void hideLoader() {
        if (loadingDialog != null && loadingDialog.isShowing() && !isFinishing()) {
            loadingDialog.dismiss();
        }

        if (srlDevices.isRefreshing()) {
            srlDevices.setRefreshing(false);
        }
    }


    @Override
    public void onUnknownError(String error) {
        showSingleButtonDialog(getString(R.string.error), error);
    }

    @Override
    public void onTimeout() {
        showSingleButtonDialog(getString(R.string.timeout_title), getString(R.string.timeout_body));
    }

    @Override
    public void onNetworkError() {
        showSingleButtonDialog(getString(R.string.network_error_title), getString(R.string.network_error_body));
    }

    @Override
    public void onConnectionError() {
        showNoInternetHeader();
    }

    @Override
    public void logoutUser() {

        mPresenter.clearUserData(this);
        setResult(ActivityRequestCodes.LOGOUT_RESULT_CODE);

        Intent intent = new Intent(this, WalkthroughActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void showNoInternetHeader() {
        AnimUtils.slideInTop(llNoInternetHeader, 300, new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llNoInternetHeader.setVisibility(View.VISIBLE);
                hideNoInternetHeader();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        }, new AccelerateInterpolator());
    }

    public void hideNoInternetHeader() {
        new Handler().postDelayed(() -> {
            AnimUtils.slideOutTop(llNoInternetHeader, 300, new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    llNoInternetHeader.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }, 3000);
    }

    @Override
    public boolean checkConnection() {
        return ConnectionUtils.userHasConnection(this);
    }

    @Override
    public void setDevicesAdapter(List<Device> devices) {


        if (srlDevices.isRefreshing()) {
            srlDevices.setRefreshing(false);
        }
        devicesAdapter = new DevicesAdapter(devices, (device, position) -> DialogUtils.showTwoButtonDialog(getString(R.string.are_you_sure), getString(R.string.unlink_device_warning), DevicesActivity.this, new TwoButtonDialogListener() {
            @Override
            public void onYesClicked() {
                mPresenter.unlinkDevice(device, position);
            }

            @Override
            public void onNoClicked() {
            }
        }));

        rvDevices.setAdapter(devicesAdapter);
    }

    @Override
    public void finishDevicesActivityWithUnlinkedResult() {
        setResult(RESULT_OK);
        finish();
        overridePendingTransition(R.anim.slide_in_from_left_fast, R.anim.slide_out_right);
    }

    @Override
    public void finishDevicesActivityWithNoResult() {
        setResult(RESULT_CANCELED);
        finish();
        overridePendingTransition(R.anim.slide_in_from_left_fast, R.anim.slide_out_right);
    }

    @Override
    public void showSingleButtonDialog(String title, String message) {
        if (!isFinishing()) {
            try {
                DialogUtils.showSingleButtonDialog(title, message, this, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void removeItemFromAdapter(int position) {
        devicesAdapter.remove(position);
    }

    @Override
    public void onBackPressed() {
        finishDevicesActivityWithUnlinkedResult();
    }
}

