package ch.pizzalemon.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.widget.TextView;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.adapter.pager.CampaignBannerPagerAdapter;
import ch.pizzalemon.android.api.ApiConstants;
import ch.pizzalemon.android.api.ApiEndPoints;
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.PriceHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import ch.pizzalemon.android.model.AppVersionModel;
import ch.pizzalemon.android.model.CampaignBannerModel;
import ch.pizzalemon.android.model.CategoryModel;
import ch.pizzalemon.android.model.StoreModel;
import ch.pizzalemon.android.model.WelcomeMessageModel;
import ch.pizzalemon.android.model.cart.CartInfoModel;
import me.relex.circleindicator.CircleIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashActivity extends BaseActivity {

    @BindView(R.id.postCodeTextView) TextView postCodeTextView;
    @BindView(R.id.campaignsViewPager) ViewPager campaignsViewPager;
    @BindView(R.id.viewPagerIndicator) CircleIndicator viewPagerIndicator;

    @BindString(R.string.alert_invalid_post_code) String choosePostCodeAlert;

    private ArrayList<StoreModel> storeList = new ArrayList<>();
    private ArrayList<CampaignBannerModel> campaignBannerList = new ArrayList<>();
    private StoreModel selectedStoreModel;
    private CampaignBannerPagerAdapter campaignBannerPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        //DisplayHelper.changeStatusColor();
        if(NetworkHelper.isNetworkAvailable()){
            registerNotificationTag();
            getSessionId();
        }
        else{
            DialogHelper.showNoNetworkDialog();
        }
    }

    private void initCampaignViewPager(){
        campaignBannerPagerAdapter = new CampaignBannerPagerAdapter(getSupportFragmentManager(), campaignBannerList);
        campaignsViewPager.setAdapter(campaignBannerPagerAdapter);
        viewPagerIndicator.setViewPager(campaignsViewPager);
        viewPagerIndicator.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.choosePostCodeLayout, R.id.choosePostCodeButton})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.choosePostCodeLayout:
                showStoreListDialog();
                break;
            case R.id.choosePostCodeButton:
                if(selectedStoreModel == null){
                    DialogHelper.showAlertDialog(BaseActivity.currentActivity, choosePostCodeAlert);
                }
                else {
                    checkVersion();
                }
                break;
        }
    }

    private void registerNotificationTag(){
        if(SessionHelper.isFirstTime()) {
            OneSignal.sendTag(
                    ApiConstants.ONESIGNAL_NOTIFICATION_TAG_KEY,
                    ApiConstants.ONESIGNAL_NOTIFICATION_TAG_VALUE);
            SessionHelper.setIsFirstTime(false);
        }
    }

    private void getSessionId(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<String>> call = ApiService.apiInterface.getSessionId();
        call.enqueue(new Callback<ResponseObject<String>>() {
            @Override
            public void onResponse(Call<ResponseObject<String>> call, Response<ResponseObject<String>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess() && !response.body().getData().isEmpty()){
                    SessionHelper.saveSessionId(response.body().getData());
                    getStoreList();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void getStoreList(){
        Call<ResponseArray<StoreModel>> call = ApiService.apiInterface.getStoreList();
        call.enqueue(new Callback<ResponseArray<StoreModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<StoreModel>> call, Response<ResponseArray<StoreModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess() && !response.body().getData().isEmpty()){
                    storeList.addAll(response.body().getData());
                    getCampaignBanners();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void getCampaignBanners(){
        Call<ResponseArray<CampaignBannerModel>> call = ApiService.apiInterface.getCampaignBanners();
        call.enqueue(new Callback<ResponseArray<CampaignBannerModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<CampaignBannerModel>> call, Response<ResponseArray<CampaignBannerModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    campaignBannerList.clear();
                    campaignBannerList.addAll(response.body().getData());
                    sortCampaignBannerList();
                    initCampaignViewPager();
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void showStoreListDialog(){

        Collections.sort(storeList, new Comparator<StoreModel>() {
            @Override
            public int compare(StoreModel s1, StoreModel s2) {
                return s1.getPostCode().compareTo(s2.getPostCode());
            }
        });

        final ArrayList<String> postCodeList = new ArrayList<>();
        for(StoreModel storeModel : storeList){
            storeModel.checkNull();
            postCodeList.add(storeModel.getPostCode() + "-" + storeModel.getCity());
        }

        DialogHelper.showStoreListDialog(postCodeList, new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                selectedStoreModel = storeList.get(position);
                postCodeTextView.setText(selectedStoreModel.getPostCode() + "-" + selectedStoreModel.getCity());
                SessionHelper.setSelectedStore(selectedStoreModel);
                ApiService.getInstance().reset();

            }
        });
    }

    private void checkVersion(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<AppVersionModel>> call = ApiService.apiInterface.checkUpdate(
                SessionHelper.getSelectedStore().getStoreName(),
                getCheckUpdateParams());
        call.enqueue(new Callback<ResponseObject<AppVersionModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<AppVersionModel>> call, Response<ResponseObject<AppVersionModel>> response) {
                if(response.isSuccessful()){
                    if(response.body().isSuccess()){
                        getWelcomeMessage();
                    }
                    else{
                        DialogHelper.hideLoadingDialog();
                        DialogHelper.showUpdateAppDialog(SplashActivity.this);
                    }
                }
                else{
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void getWelcomeMessage(){
        Call<ResponseObject<WelcomeMessageModel>> call = ApiService.apiInterface.getWelcomeMessage(
                SessionHelper.getSelectedStore().getStoreName());
        call.enqueue(new Callback<ResponseObject<WelcomeMessageModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<WelcomeMessageModel>> call, Response<ResponseObject<WelcomeMessageModel>> response) {
                if(response.isSuccessful()){
                    if(response.body().isSuccess()){
                        if(response.body().getData().isShowDialog()){
                            DialogHelper.hideLoadingDialog();
                            showWelcomeDialog(response.body().getData());
                        }
                        else {
                            getCategoryList();
                        }
                    }
                    else{
                        DialogHelper.hideLoadingDialog();
                        DialogHelper.showUpdateAppDialog(SplashActivity.this);
                    }
                }
                else{
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void showWelcomeDialog(final WelcomeMessageModel welcomeMessageModel){
        DialogHelper.showOneButtonDialogWithCallback(
                welcomeMessageModel.getMessage(),
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if(welcomeMessageModel.isClosable()){
                            DialogHelper.showLoadingDialog();
                            getCategoryList();
                        }
                        else {
                            finishAffinity();
                        }
                    }
                },
                false);
    }

    private HashMap<String, Object> getCheckUpdateParams(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("application", ApiConstants.APP_TYPE_ID_ANDROID);
        params.put("version", getAppVersionCode());
        return params;
    }

    private void getCategoryList(){
        Call<ResponseArray<CategoryModel>> call = ApiService.apiInterface.getAllCategories(SessionHelper.getSelectedStore().getStoreName());
        call.enqueue(new Callback<ResponseArray<CategoryModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<CategoryModel>> call, Response<ResponseArray<CategoryModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    saveCategoryList(response.body().getData());
                    getPizzaCategoryIds();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void saveCategoryList(ArrayList<CategoryModel> categoryList){
        CategoryModel versionNameCategoryModel = new CategoryModel();
        versionNameCategoryModel.setId(ApiConstants.PRODUCT_ID_VERSION_MENU);
        versionNameCategoryModel.setName("v" + getAppVersionName());
        categoryList.add(versionNameCategoryModel);
        CategoryModel.checkNull(categoryList);
        SharedPrefsHelper.saveCategoryList(categoryList);
    }

    private void getPizzaCategoryIds(){
        Call<ResponseArray<Integer>> call = ApiService.apiInterface.getPizzaCategoryIds(SessionHelper.getSelectedStore().getStoreName());
        call.enqueue(new Callback<ResponseArray<Integer>>() {
            @Override
            public void onResponse(Call<ResponseArray<Integer>> call, Response<ResponseArray<Integer>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.savePizzaCategoryIdList(response.body().getData());
                    getIgnoredCategoryIds();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void getIgnoredCategoryIds(){
        Call<ResponseArray<Integer>> call = ApiService.apiInterface.getIgnoredCategoryIds(SessionHelper.getSelectedStore().getStoreName());
        call.enqueue(new Callback<ResponseArray<Integer>>() {
            @Override
            public void onResponse(Call<ResponseArray<Integer>> call, Response<ResponseArray<Integer>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.saveIgnoredCategoryIdList(response.body().getData());
                    checkCustomerToken();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    /*
    private void checkCustomerToken(){

        if(SessionHelper.isCustomerLoggedIn()){
            if(SessionHelper.getCustomerToken().isCustomerTokenAlive())
                getCartItemCount();
            else
                refreshCustomerToken();
        }
        else
            openActivity(LoginActivity.class);
    }
    */

    private void checkCustomerToken(){
        if(SessionHelper.isCustomerLoggedIn()){
            getCartItemCount();
        }
        else{
            openActivity(LoginActivity.class);
        }
    }

    private void openActivity(final Class<?> cls){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(SplashActivity.this, cls));
                DialogHelper.hideLoadingDialog();
                finish();
            }
        }, 1000);
    }

    private void refreshCustomerToken(){
        /*
        Call<RefreshTokenResponseModel> call = ApiService.apiInterface.refreshCustomerToken(SessionManager.getCustomerToken().getRefreshToken());
        call.enqueue(new Callback<RefreshTokenResponseModel>() {
            @Override
            public void onResponse(Call<RefreshTokenResponseModel> call, Response<RefreshTokenResponseModel> response) {

                ApiService.getInstance().reset();

                if(response.isSuccessful() && response.body().isSuccess()) {
                    SessionManager.saveCustomerToken(response.body().getCustomerToken(), Constants.PUSULA_CARD_MEMBER_TYPE_CUSTOMER);
                    getCartItemCount();
                }

                else{
                DialogHelper.hideLoadingDialog();
                    DialogHelper.showAlertDialog(BaseActivity.currentActivity, "Bir hata oluştu. Lütfen daha sonra tekrar deneyin.");
                    }
            }

            @Override
            public void onFailure(Call<RefreshTokenResponseModel> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                ApiService.getInstance().reset();
                DialogHelper.showAlertDialog(BaseActivity.currentActivity, "Bir hata oluştu. Lütfen daha sonra tekrar deneyin.");
            }
        });
        */
    }

    private void getCartItemCount(){
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
                */

        HashMap<String, Object> params = new HashMap<>();
        SessionHelper.addCouponCodeToRequestParamsIfNeeded(params);

        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                params);

        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getCartTotalModel().getText()));
                    openActivity(MainActivity.class);

                }
                else {
                    DialogHelper.hideLoadingDialog();
                    //response.body().getErrorCode()
                    ApiErrorUtils.parseError(response);
                }
            }

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


    private void sortCampaignBannerList(){
        ArrayList<CampaignBannerModel> tempList = new ArrayList<>();
        for(CampaignBannerModel campaignBannerModel : campaignBannerList){
            if(campaignBannerModel.isActive()){
                tempList.add(campaignBannerModel);
            }
        }
        campaignBannerList.clear();
        campaignBannerList.addAll(tempList);
        tempList.clear();
        Collections.sort(campaignBannerList, new Comparator<CampaignBannerModel>() {
            @Override
            public int compare(CampaignBannerModel b1, CampaignBannerModel b2) {
                return b1.getOrder().compareTo(b2.getOrder());
            }
        });
    }


}
