package ch.pizzalemon.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.onesignal.OneSignal;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.activity.MyAddressesActivity;
import ch.pizzalemon.android.activity.SplashActivity;
import ch.pizzalemon.android.activity.UpdatePasswordActivity;
import ch.pizzalemon.android.activity.UpdateProfileActivity;
import ch.pizzalemon.android.adapter.recycler.PersonalCouponCodesRecyclerAdapter;
import ch.pizzalemon.android.api.ApiConstants;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseArray;
import ch.pizzalemon.android.api.ResponseObject;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.NetworkHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import ch.pizzalemon.android.model.PersonalCouponModel;
import ch.pizzalemon.android.model.UserModel;
import ch.pizzalemon.android.view.AppInfoView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by cimenmus on 18/09/2017.
 */

public class ProfileFragment extends BaseFragment {

    @BindView(R.id.firstnamePizzalinkInfoLayout) AppInfoView firstnamePizzalinkInfoLayout;
    @BindView(R.id.lastnamePizzalinkInfoLayout) AppInfoView lastnamePizzalinkInfoLayout;
    @BindView(R.id.emailPizzalinkInfoLayout) AppInfoView emailPizzalinkInfoLayout;
    @BindView(R.id.phonePizzalinkInfoLayout) AppInfoView phonePizzalinkInfoLayout;
    @BindView(R.id.enableNotificationsSwitch) SwitchCompat enableNotificationsSwitch;
    @BindView(R.id.personalCouponCodesTextView) TextView personalCouponCodesTextView;
    @BindView(R.id.personalCouponCodesRecyclerView) RecyclerView personalCouponCodesRecyclerView;

    @BindString(R.string.bottom_nav_menu_item_profile) String fragmentTitle;
    @BindString(R.string.alert_logout) String logoutAlertText;
    @BindString(R.string.something_went_wrong) String genericErrorText;

    public static final java.lang.String FRAGMENT_NAME = "profileFragment";
    private int REQUEST_CODE_UPDATE_PROFILE = 2563;

    private UserModel userModel;
    private PersonalCouponCodesRecyclerAdapter personalCouponCodesRecyclerAdapter;

    public ProfileFragment() {}

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        ButterKnife.bind(this, view);
        initViews();
        getCustomerProfile();
        getNotificationStatus();
        return view;
    }

    @OnClick({R.id.myAddressesLayout, R.id.updatePasswordLayout,
            R.id.updateProfileLayout, R.id.changePostCodeLayout,
            R.id.logoutLayout})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.myAddressesLayout:
                startActivity(new Intent(BaseActivity.currentActivity, MyAddressesActivity.class));
                break;
            case R.id.updateProfileLayout:
                Intent updateProfileIntent = new Intent(BaseActivity.currentActivity, UpdateProfileActivity.class);
                updateProfileIntent.putExtra("userModel", userModel);
                startActivityForResult(updateProfileIntent, REQUEST_CODE_UPDATE_PROFILE);
                break;
            case R.id.updatePasswordLayout:
                startActivity(new Intent(BaseActivity.currentActivity, UpdatePasswordActivity.class));
                break;
            case R.id.changePostCodeLayout:
                BaseActivity.currentActivity.startActivity(new Intent(BaseActivity.currentActivity, SplashActivity.class));
                BaseActivity.currentActivity.finishAffinity();
                break;
            case R.id.logoutLayout:
                DialogHelper.showTwoButtonsDialog(BaseActivity.currentActivity, logoutAlertText,
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                logOutOnWeb();
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        });
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_UPDATE_PROFILE &&
                resultCode == RESULT_OK){
            userModel = SessionHelper.getUser();
            firstnamePizzalinkInfoLayout.setText(userModel.getFirstname());
            lastnamePizzalinkInfoLayout.setText(userModel.getLastname());
            emailPizzalinkInfoLayout.setText(userModel.getEmail());
            phonePizzalinkInfoLayout.setText(userModel.getTelephone());
        }
    }

    private void initViews(){
        setPizzalinkToolbarFields(false, fragmentTitle);
        enableNotificationsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                setNotificationStatus();
            }
        });
    }

    private void getNotificationStatus(){
        OneSignal.getTags(new OneSignal.OSGetTagsHandler() {
            @Override
            public void tagsAvailable(JSONObject tags) {
                BaseActivity.currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(tags != null &&
                                !tags.toString().isEmpty() &&
                                tags.toString().contains(ApiConstants.ONESIGNAL_NOTIFICATION_TAG_KEY)){
                            enableNotificationsSwitch.setChecked(true);
                        }
                        else {
                            enableNotificationsSwitch.setChecked(false);
                        }
                    }
                });
            }
        });
    }

    private void setNotificationStatus(){
        if(!NetworkHelper.isNetworkAvailable()){
            DialogHelper.showNoNetworkDialog();
            return;
        }

        DialogHelper.showLoadingDialog();

        if(enableNotificationsSwitch.isChecked()) {

            JSONObject tags = new JSONObject();
            try {
                tags.put(ApiConstants.ONESIGNAL_NOTIFICATION_TAG_KEY, ApiConstants.ONESIGNAL_NOTIFICATION_TAG_VALUE);
                OneSignal.sendTags(tags, new OneSignal.ChangeTagsUpdateHandler() {
                    @Override
                    public void onSuccess(JSONObject tags) {
                        DialogHelper.hideLoadingDialog();
                    }

                    @Override
                    public void onFailure(OneSignal.SendTagsError error) {
                        DialogHelper.hideLoadingDialog();
                        DialogHelper.showAlertDialog(BaseActivity.currentActivity, genericErrorText);
                    }
                });
            }
            catch (JSONException e){
                e.printStackTrace();
                DialogHelper.hideLoadingDialog();
                DialogHelper.showAlertDialog(BaseActivity.currentActivity, genericErrorText);
            }

        }
        else {
            OneSignal.deleteTag(
                    ApiConstants.ONESIGNAL_NOTIFICATION_TAG_KEY,
                    new OneSignal.ChangeTagsUpdateHandler() {
                        @Override
                        public void onSuccess(JSONObject tags) {
                            DialogHelper.hideLoadingDialog();
                        }

                        @Override
                        public void onFailure(OneSignal.SendTagsError error) {
                            DialogHelper.hideLoadingDialog();
                            DialogHelper.showAlertDialog(BaseActivity.currentActivity, genericErrorText);
                        }
                    }
            );
        }
    }

    private void getCustomerProfile(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<UserModel>> call = ApiService.apiInterface.getCustomerProfile(
                SessionHelper.getSelectedStore().getStoreName(),
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject<UserModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<UserModel>> call, Response<ResponseObject<UserModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    setFields(response.body().getData());
                    getPersonalCouponCodeList();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

            @Override
            public void onFailure(Call<ResponseObject<UserModel>> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void getPersonalCouponCodeList(){
        Call<ResponseArray<PersonalCouponModel>> call = ApiService.apiInterface.getPersonalCouponList(
                SessionHelper.getSelectedStore().getStoreName(),
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseArray<PersonalCouponModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<PersonalCouponModel>> call, Response<ResponseArray<PersonalCouponModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    initPersonalCouponCodesRecyclerView(response.body().getData());
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

            @Override
            public void onFailure(Call<ResponseArray<PersonalCouponModel>> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void setFields(UserModel user){

        user.checkNull();
        userModel = user;
        SessionHelper.saveCustomer(userModel);

        firstnamePizzalinkInfoLayout.setText(userModel.getFirstname());
        lastnamePizzalinkInfoLayout.setText(userModel.getLastname());
        emailPizzalinkInfoLayout.setText(userModel.getEmail());
        phonePizzalinkInfoLayout.setText(userModel.getTelephone());
    }

    private void initPersonalCouponCodesRecyclerView(ArrayList<PersonalCouponModel> personalCouponList){

        if(personalCouponList == null || personalCouponList.isEmpty()){
            personalCouponCodesTextView.setVisibility(View.GONE);
            personalCouponCodesRecyclerView.setVisibility(View.GONE);
            return;
        }

        ArrayList<PersonalCouponModel> filteredPersonalCouponList = new ArrayList<>();
        for(PersonalCouponModel personalCouponModel: personalCouponList){
            if(filteredPersonalCouponList.size() == 10){
                break;
            }
            filteredPersonalCouponList.add(personalCouponModel);
        }

        personalCouponCodesTextView.setVisibility(View.VISIBLE);
        personalCouponCodesRecyclerView.setVisibility(View.VISIBLE);
        personalCouponCodesRecyclerAdapter = new PersonalCouponCodesRecyclerAdapter(BaseActivity.currentActivity, filteredPersonalCouponList);
        personalCouponCodesRecyclerView.setLayoutManager(new LinearLayoutManager(BaseActivity.currentActivity));
        personalCouponCodesRecyclerView.setNestedScrollingEnabled(false);
        personalCouponCodesRecyclerView.setAdapter(personalCouponCodesRecyclerAdapter);
    }

    private void logOutOnWeb(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject> call = ApiService.apiInterface.logout(
                SessionHelper.getSelectedStore().getStoreName(),
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() && response.body().isSuccess())
                    logoutLocally();
                else
                    ApiErrorUtils.parseError(response);
            }

            @Override
            public void onFailure(Call<ResponseObject> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void logoutLocally(){
        SharedPrefsHelper.clearCustomerInfo();
        SharedPrefsHelper.clearCustomerToken();
        SharedPrefsHelper.setCustomerLoggedIn(false);
        SharedPrefsHelper.clearSelectedStore();
        ApiService.getInstance().reset();
        BaseActivity.currentActivity.startActivity(new Intent(BaseActivity.currentActivity, SplashActivity.class));
        BaseActivity.currentActivity.finishAffinity();
    }
}
