package ch.pizzalink.android.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import ch.pizzalink.android.R;
import ch.pizzalink.android.api.ApiConstants;
import ch.pizzalink.android.api.ApiErrorUtils;
import ch.pizzalink.android.api.ApiService;
import ch.pizzalink.android.api.ResponseArray;
import ch.pizzalink.android.api.ResponseObject;
import ch.pizzalink.android.helper.DialogHelper;
import ch.pizzalink.android.helper.DisplayHelper;
import ch.pizzalink.android.helper.NetworkHelper;
import ch.pizzalink.android.helper.PriceHelper;
import ch.pizzalink.android.helper.SessionHelper;
import ch.pizzalink.android.helper.SharedPrefsHelper;
import ch.pizzalink.android.model.AppVersionModel;
import ch.pizzalink.android.model.CategoryModel;
import ch.pizzalink.android.model.cart.CartInfoModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashActivity extends BaseActivity {

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

    private void checkVersion(){
        Call<ResponseObject<AppVersionModel>> call = ApiService.apiInterface.checkUpdate(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()){
                        getCategoryList();
                    }
                    else{
                        DialogHelper.showUpdateAppDialog(SplashActivity.this);
                    }
                }
                else{
                    ApiErrorUtils.parseError(response);
                }
            }

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

    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 int getAppVersionCode(){
        PackageInfo pInfo = null;
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
        return pInfo.versionCode;
    }

    private void getCategoryList(){
        Call<ResponseArray<CategoryModel>> call = ApiService.apiInterface.getAllCategories();
        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()){
                    CategoryModel.checkNull(response.body().getData());
                    SharedPrefsHelper.saveCategoryList(response.body().getData());
                    getIgnoredCategoryIds();
                }
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void getIgnoredCategoryIds(){
        Call<ResponseArray<Integer>> call = ApiService.apiInterface.getIgnoredCategoryIds();
        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 {
                    ApiErrorUtils.parseError(response);
                }
            }

            @Override
            public void onFailure(Call<ResponseArray<Integer>> call, Throwable t) {
                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));
                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.showAlertDialog(BaseActivity.currentActivity, "Bir hata oluştu. Lütfen daha sonra tekrar deneyin.");
            }

            @Override
            public void onFailure(Call<RefreshTokenResponseModel> call, Throwable t) {
                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.getCustomerToken().getToken());
        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().getTotals().get(0).getText()));
                    openActivity(MainActivity.class);

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

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




}
