package com.droideve.apps.dealify.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.FragmentManager;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.balysv.materialripple.MaterialRippleLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.droideve.apps.dealify.AppController;
import com.droideve.apps.dealify.classes.Category;
import com.droideve.apps.dealify.classes.User;
import com.droideve.apps.dealify.customview.ProductImageCarousel;
import com.droideve.apps.dealify.customview.ProductCustomView;
import com.droideve.apps.dealify.fragments.orderFrags.ProductVariantFragment;
import com.droideve.apps.dealify.location.GPStracker;
import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.animation.ImageLoaderAnimation;
import com.droideve.apps.dealify.appconfig.AppConfig;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Cart;
import com.droideve.apps.dealify.classes.Images;
import com.droideve.apps.dealify.classes.Product;
import com.droideve.apps.dealify.classes.Store;
import com.droideve.apps.dealify.controllers.CampagneController;
import com.droideve.apps.dealify.controllers.ProductsAnalyticsController;
import com.droideve.apps.dealify.controllers.SettingsController;
import com.droideve.apps.dealify.controllers.cart.CartController;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.controllers.stores.ProductsController;
import com.droideve.apps.dealify.controllers.stores.StoreController;
import com.droideve.apps.dealify.fragments.SlideshowDialogFragment;
import com.droideve.apps.dealify.load_manager.ViewManager;
import com.droideve.apps.dealify.network.ServiceHandler;
import com.droideve.apps.dealify.network.VolleySingleton;
import com.droideve.apps.dealify.network.api_request.ApiRequest;
import com.droideve.apps.dealify.network.api_request.ApiRequestListeners;
import com.droideve.apps.dealify.network.api_request.SimpleRequest;
import com.droideve.apps.dealify.parser.Parser;
import com.droideve.apps.dealify.parser.api_parser.ProductParser;
import com.droideve.apps.dealify.parser.api_parser.StoreParser;
import com.droideve.apps.dealify.utils.DateUtils;
import com.droideve.apps.dealify.utils.NSLog;
import com.droideve.apps.dealify.utils.NSToast;
import com.droideve.apps.dealify.utils.ProductUtils;
import com.droideve.apps.dealify.utils.TextUtils;
import com.droideve.apps.dealify.utils.Utils;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.nirhart.parallaxscroll.views.ParallaxScrollView;
import com.wuadam.awesomewebview.AwesomeWebView;

import org.bluecabin.textoo.LinksHandler;
import org.bluecabin.textoo.Textoo;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;
import io.realm.Realm;
import io.realm.RealmList;

import static com.droideve.apps.dealify.appconfig.AppConfig.APP_DEBUG;


public class ProductDetailActivity extends GlobalActivity implements ViewManager.CustomView, GlobalActivity.CustomScrollListener {

    @BindView(R.id.app_bar)
    Toolbar toolbar;

    @BindView(R.id.progressBar)
    SpinKitView progressBar;
    @BindView(R.id.loading)
    LinearLayout loading;
    @BindView(R.id.toolbar_back)
    ImageView toolbar_back;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.product_label)
    TextView product_label;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.stock)
    TextView stock;
    @BindView(R.id.priceView)
    TextView priceView;
    @BindView(R.id.old_price)
    TextView old_price;
    @BindView(R.id.productName)
    TextView productName;
    @BindView(R.id.categoriesContainer)
    LinearLayout categoriesContainer;
    @BindView(R.id.detail_product)
    TextView detailProduct;
    @BindView(R.id.product_up_to)
    TextView productUpTo;
    @BindView(R.id.storeBtn)
    TextView storeBtn;
    @BindView(R.id.storeBtnLayout)
    LinearLayout storeBtnLayout;

    @BindView(R.id.deal_layout)
    LinearLayout dealLayout;

    @BindView(R.id.btn_custom_order)
    AppCompatButton btnCustomOrder;

    @BindView(R.id.bottomBtnAddToBookmarkBtn)
    MaterialRippleLayout bottomBtnAddToBookmarkBtn;

    @BindView(R.id.imageCarousel)
    ProductImageCarousel imageCarousel;

    @BindView(R.id.mScroll)
    NestedScrollView mScroll;


    private Store relatedStore;

    @OnClick(R.id.bottomBtnAddToBookmarkBtn)
    void onBottomAddToBookmarkClick(View view) {
        bookMarkToggle();
    }

    @OnClick(R.id.btn_custom_order)
    void onOrderClick(View view) {

        //check if order is associated t the opening time
        if (productData.getStore_order_enabled() == 1 && productData.getStore_order_based_on_op() == 1) {

            if (StoreController.getStore(productData.getStore_id()) != null) {
                relatedStore = StoreController.getStore(productData.getStore_id());
            } else {
                syncStoreFromAPI(productData.getStore_id());
            }

            if (relatedStore != null)
                if (relatedStore.getOpening() < 0  ) {  // if store is closed disable button click
                    NSToast.show(relatedStore.getName() + getString(R.string.store_closed_order));
                    return;
                }
        }


        if (SessionsController.isLogged()) {

            //check pickup from
            if (!CartController.checkProductStore(productData.getStore_id(), SessionsController.getSession().getUser().getId())) {
                NSToast.show(getString(R.string.order_items_error));
                return;
            }

            //check product stock
            if (productData.getStock() == 0) {
                NSToast.show(getString(R.string.out_of_stock));
                return;
            }


            //fill cart detail
            Cart mCart = new Cart();
            mCart.setModule_id(productData.getId());
            mCart.setModule(Constances.ModulesConfig.PRODUCT_MODULE);
            mCart.setAmount(productData.getProduct_value());
            mCart.setProduct(productData);
            mCart.setQte(1);

            mCart.setParent_id(productData.getStore_id());
            mCart.setUser_id(SessionsController.getSession().getUser().getId());


            //check if the product has  variants
            if (productData.getVariants() != null && productData.getVariants().size() > 0) {

                Intent intent = new Intent(ProductDetailActivity.this, ProductVariantsActivity.class);

                intent.putExtra("module_id", productData.getId());
                intent.putExtra("module", Constances.ModulesConfig.PRODUCT_MODULE);

                startActivity(intent);
                
                finish();

            } else {
                if (productData.getQty_enabled() > 0) {
                    showBottomSheetDialog(mCart);
                } else {
                    Intent intent = new Intent(new Intent(ProductDetailActivity.this, OrderCheckoutActivity.class));

                    //save cart in the database
                    CartController.addProductToCard(mCart);

                    intent.putExtra("module_id", productData.getId());
                    intent.putExtra("module", Constances.ModulesConfig.PRODUCT_MODULE);

                    startActivity(intent);
                    
                    finish();

                }
            }


        } else {
            Intent intent = new Intent(ProductDetailActivity.this, LoginV2Activity.class);
            startActivity(intent);
            finish();
        }

    }

    private int product_id = 0;
    private ViewManager mViewManager;
    private Product productData;
    private Menu menuContext;

    // custom quantity fields
    private int custom_qte = 1;
    private float custom_price = -1;
    private float original_price = -1;

    private HashMap<String, Object> cartlist;


    private void setBookmarkIcons() {

        //Bottom Icon
        if ( (SessionsController.isLogged() && productData.getSaved() > 0)) {
            Drawable ic_fav = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_favourite,null);
            ic_fav.setTint(ResourcesCompat.getColor(getResources(),R.color.favourite_color,null));
            ((ImageView)bottomBtnAddToBookmarkBtn.findViewById(R.id.bottomBtnAddToBookmarkIcon)).setImageDrawable(ic_fav);
        } else {
            Drawable ic_fav = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_favourite_outline,null);
            ic_fav.setTint(ResourcesCompat.getColor(getResources(),R.color.favourite_color,null));
            ((ImageView)bottomBtnAddToBookmarkBtn.findViewById(R.id.bottomBtnAddToBookmarkIcon)).setImageDrawable(ic_fav);
        }

    }


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

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);

        setupToolbar();

        cartlist = new HashMap<>();

        //INIT VIEW MANAGER
        mViewManager = new ViewManager(this);
        mViewManager.setLoadingLayout(findViewById(R.id.loading));
        mViewManager.setResultLayout(findViewById(R.id.content_product));
        mViewManager.setErrorLayout(findViewById(R.id.error));
        mViewManager.setEmpty(findViewById(R.id.empty));
        mViewManager.setCustumizeView(this);

        mViewManager.loading();


        try {


            //get it from external url (deep linking)
            if (product_id == 0) {
                try {

                    Intent appLinkIntent = getIntent();
                    String appLinkAction = appLinkIntent.getAction();
                    Uri appLinkData = appLinkIntent.getData();

                    if (appLinkAction != null && appLinkAction.equals(Intent.ACTION_VIEW)) {
                        product_id = Utils.dp_get_id_from_url(appLinkData.toString(), "product_id");

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (product_id == 0)
                product_id = getIntent().getExtras().getInt("product_id");


            if (product_id == 0)
                product_id = getIntent().getExtras().getInt("id");



        } catch (Exception e) {
            e.printStackTrace();
            finish();
        }

        final Product mProduct = ProductsController.findProductById(product_id);

        //OFFLINE MODE
        if (ServiceHandler.isNetworkAvailable(this)) {
            getProduct(product_id);

            //product counter
            ProductsAnalyticsController.views(product_id);

        } else {
            if (mProduct != null && mProduct.isLoaded() && mProduct.isValid()) {
                productData = mProduct;
                setupViews();
                mViewManager.showResult();
            } else {
                getProduct(product_id);
            }
        }


        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (productData != null && productData.getListImages().size() > 0) {
                    List<Images> listProductsImg = productData.getListImages();
                    SlideshowDialogFragment.newInstance().show(ProductDetailActivity.this, listProductsImg, 0);
                }


            }
        });




        String date = "";


        try {
            date = mProduct.getDate_start();
            date = DateUtils.prepareOutputDate(date, "dd MMMM yyyy  hh:mm", this);
        } catch (Exception e) {

            getProduct(product_id);
            return;

        }


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        menuContext = menu;

        /////////////////////////////
        menu.findItem(R.id.share).setVisible(true);
        menu.findItem(R.id.report_icon).setVisible(true);

        toolbarAndScroll();

        return true;
    }

    private void setupViews() {

        toolbarTitle.setText(productData.getName());
        product_label.setText(productData.getName());


        parseProductValue(priceView, -1);


        setupProductImage();

        //setup Product description
       setupProductDescription();

       //mark the client was seen the notification compaoign
       markAsCampaignReceived();

        Drawable storeDrawable = new IconicsDrawable(this)
                .icon(CommunityMaterial.Icon.cmd_calendar)
                .color(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null))
                .sizeDp(18);
        productUpTo.setCompoundDrawables(storeDrawable, null, null, null);
        productUpTo.setCompoundDrawablePadding(20);


        //setup store information
        setupStoreInformation();

        //setup and display count down of the deal
        setupCountDown();

        //setup and display order button
        setupOrderButton();

        //setup menu icons
        setBookmarkIcons();

        //setup product variants
        setupVariants();

        //load related products
        relatedProducts();

        setupImageCarousel();

        setupProductCategories();

    }


    private void toolbarAndScroll(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            menuContext.findItem(R.id.report_icon).setIconTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.white));
            menuContext.findItem(R.id.share).setIconTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.white));
        }
        final Drawable upArrow = getResources().getDrawable(R.drawable.back);
        upArrow.setColorFilter(ResourcesCompat.getColor(getResources(),R.color.white,null) , PorterDuff.Mode.SRC_ATOP) ;
        getSupportActionBar().setHomeAsUpIndicator(upArrow);

    }

    private void setupProductImage(){

        if (productData.getImages() == null)
            return;


        Glide.with(getBaseContext())
                .asBitmap()
                .load(productData.getListImages().get(0).getUrl500_500())
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap,
                                                Transition<? super Bitmap> transition) {

                        int w =  bitmap.getWidth();
                        int h = bitmap.getHeight();

                        float ratio = (float) w/h;

                        image.setImageBitmap(bitmap);
                        //setup scroll with header
                        setupScrollNHeaderCustomized(
                                mScroll,
                                (LinearLayout) findViewById(R.id.imageContainer),
                                ratio,
                                null
                        );

                    }
                });


        scrollListener = this;
    }

    private void setupImageCarousel(){

       /* imageCarousel.setup(this);
        for (int i=0;i<productData.getListImages().size();i++){
            Images im = productData.getListImages().get(i);

            int finalI = i;
            imageCarousel.addImage(this, im.getUrl200_200(), i == 0?true:false ).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (productData != null && productData.getListImages().size() > 0) {
                        List<Images> listProductsImg = productData.getListImages();
                        SlideshowDialogFragment.newInstance().show(ProductDetailActivity.this, listProductsImg, finalI);
                    }
                }
            });
        }*/

        imageCarousel.setVisibility(View.GONE);

    }


    private void setupProductCategories(){

        LayoutInflater inflater = LayoutInflater.from(this);
        categoriesContainer.removeAllViews();
        if(productData.getCategories().size()>0){
            for (Category cat : productData.getCategories()){
                View v = inflater.inflate(R.layout.category_badge, null, false);

                int color = ContextCompat.getColor(this, R.color.colorPrimary);

                try {
                    if (cat.getColor() != null && !cat.getColor().equals("null"))
                        color = Color.parseColor(cat.getColor());
                } catch (Exception e) {
                }

                TextView txt = v.findViewById(R.id.badge_category);

                Drawable badge_cat_background = txt.getBackground();
                if (badge_cat_background instanceof ShapeDrawable) {
                    ((ShapeDrawable) badge_cat_background).getPaint().setColor(color);
                } else if (badge_cat_background instanceof GradientDrawable) {
                    ((GradientDrawable) badge_cat_background).setColor(color);
                } else if (badge_cat_background instanceof ColorDrawable) {
                    ((ColorDrawable) badge_cat_background).setColor(color);
                }

                txt.setText(cat.getNameCat());
                categoriesContainer.addView(v);

                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap<String, Object> searchParams = new HashMap<>();
                        searchParams.put("module", Constances.ModulesConfig.PRODUCT_MODULE);
                        searchParams.put("category_id", cat.getNumCat());
                        searchParams.put("custom_title", cat.getNameCat());
                        //searchParams
                        Intent intent = new Intent(ProductDetailActivity.this, ResultFilterActivity.class);
                        intent.putExtra("searchParams", searchParams);
                        startActivity(intent);
                    }
                });
            }
            categoriesContainer.setVisibility(View.VISIBLE);
        }else{
            categoriesContainer.setVisibility(View.GONE);
        }

    }


    private void markAsCampaignReceived() {
        try {

            if (getIntent().hasExtra("cid")) {
                int cid = Integer.parseInt(getIntent().getExtras().getString("cid"));
                CampagneController.markView(cid);
            }
        } catch (Exception e) {
            if (APP_DEBUG)
                e.printStackTrace();
        }

    }

    private void setupVariants(){

        if (productData.getVariants().size()>0) {

            Bundle bundle = new Bundle();
            bundle.putInt("module_id", productData.getId());
            bundle.putString("module", "product");

            ProductVariantFragment fragment = new ProductVariantFragment();
            fragment.setArguments(bundle);

            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.product_variants_container, fragment)
                    .commit();

            findViewById(R.id.product_variants).setVisibility(View.VISIBLE);

        }else {
            findViewById(R.id.product_variants).setVisibility(View.GONE);
        }
    }

    private void setupStoreInformation() {
        if (productData.getStore_id() > 0) {

            productName.setText(productData.getName());

            Drawable storeDrawable = new IconicsDrawable(this)
                    .icon(CommunityMaterial.Icon2.cmd_map_marker)
                    .color(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null))
                    .sizeDp(18);


            if (productData.getOriginal_value() != 0) {
                double original_price = productData.getOriginal_value();
                old_price.setText(ProductUtils.parseCurrencyFormat((float) original_price, productData.getCurrency()));
                old_price.setPaintFlags(old_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                old_price.setVisibility(View.VISIBLE);
            } else {
                old_price.setVisibility(View.GONE);
            }


            if (productData.getStock() > 0) {
                this.stock.setTextColor(ResourcesCompat.getColor(getResources(), R.color.green, null));
                this.stock.setText(getString(R.string.in_stock));
                this.stock.setVisibility(View.VISIBLE);
            } else if (productData.getStock() == 0) {
                this.stock.setTextColor(ResourcesCompat.getColor(getResources(), R.color.red, null));
                this.stock.setText(getString(R.string.out_of_stock));
                this.stock.setVisibility(View.VISIBLE);
                this.old_price.setVisibility(View.GONE);
            }else if(productData.getStock()==-1){
                this.stock.setVisibility(View.GONE);
            } else {
                this.stock.setVisibility(View.GONE);
            }

            storeBtn.setText(productData.getStore_name());

            if (AppController.isRTL()) {
                storeBtn.setCompoundDrawables(null, null, storeDrawable, null);
            } else {
                storeBtn.setCompoundDrawables(storeDrawable, null, null, null);
            }

            storeBtn.setCompoundDrawablePadding(20);
            storeBtn.setPaintFlags(storeBtn.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);


            //fixing bug reported in crashlytics : io.realm.internal.UncheckedRow.nativeGetLong
            final int store_id = productData.getStore_id();
            storeBtnLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {

                        Realm realm = Realm.getDefaultInstance();
                        realm.beginTransaction();

                        if (!StoreDetailActivity.isOpend()) {
                            Intent intent = new Intent(ProductDetailActivity.this, StoreDetailActivity.class);
                            intent.putExtra("id", store_id);
                            startActivity(intent);
                        }

                        realm.commitTransaction();

                    } catch (Exception e) {
                        if (APP_DEBUG)
                            e.printStackTrace();

                        NSToast.show(getString(R.string.store_not_found));

                    }

                }
            });

            storeBtnLayout.setVisibility(View.VISIBLE);
        } else
            storeBtnLayout.setVisibility(View.GONE);
    }

    private void setupProductDescription() {

        detailProduct.setText(productData.getDescription());
        new TextUtils.decodeHtml(detailProduct).execute(productData.getDescription());

        Textoo
                .config(detailProduct)
                .linkifyWebUrls()  // or just .linkifyAll()
                .addLinksHandler(new LinksHandler() {
                    @Override
                    public boolean onClick(View view, String url) {

                        if (Utils.isValidURL(url)) {

                            new AwesomeWebView.Builder(ProductDetailActivity.this)
                                    .showMenuOpenWith(false)
                                    .statusBarColorRes(R.color.colorPrimary)
                                    .theme(R.style.FinestWebViewAppTheme)
                                    .titleColor(
                                            ResourcesCompat.getColor(getResources(), R.color.defaultWhiteColor, null)
                                    ).urlColor(
                                            ResourcesCompat.getColor(getResources(), R.color.defaultWhiteColor, null)
                                    ).show(url);

                            return true;
                        } else {
                            return false;
                        }
                    }
                })
                .apply();
    }

    private void setupOrderButton(){

        //hide order action when store doesn't allow order option

        if (productData.getOrder_enabled() != 1
                || !SettingsController.isModuleEnabled(Constances.ModulesConfig.ORDERS_MODULE)) {
            //disable order button
            btnCustomOrder.setEnabled(false);
            return;
        }else if (productData.getStore_order_enabled() != 1){
            //disable order button
            btnCustomOrder.setEnabled(false);
            return;
        }

        btnCustomOrder.setEnabled(true);

        if (productData.getOrder_button() != null && !productData.getOrder_button().equalsIgnoreCase("")) {
            btnCustomOrder.setText(productData.getOrder_button().toUpperCase());
        }

    }

    private void parseProductValue(TextView priceView, float custom_price) {
        if (productData.getProduct_type().equalsIgnoreCase("Percent") && (productData.getProduct_value() > 0 || productData.getProduct_value() < 0)) {
            DecimalFormat decimalFormat = new DecimalFormat("#0");

            priceView.setText(String.format(getString(R.string.product_off), decimalFormat.format(productData.getProduct_value()) + "%"));
            priceView.setVisibility(View.VISIBLE);

        } else {

            if (productData.getProduct_type().equalsIgnoreCase("Price") && productData.getProduct_value() != 0) {

                priceView.setText(ProductUtils.parseCurrencyFormat(custom_price > 0 ? custom_price : productData.getProduct_value(), productData.getCurrency()));
                priceView.setVisibility(View.VISIBLE);

            } else {
                priceView.setVisibility(View.VISIBLE);
                priceView.setText(getString(R.string.promo));
            }
        }
    }

    private void setupCountDown() {

        String dateStartAt = "";
        String dateEndAt = "";


        try {
            dateStartAt = productData.getDate_start();
            dateStartAt = DateUtils.prepareOutputDate(dateStartAt, "dd MMMM yyyy", this);
        } catch (Exception e) {
            return;
        }

        try {
            dateEndAt = productData.getDate_end();
            dateEndAt = DateUtils.prepareOutputDate(dateEndAt, "dd MMMM yyyy", this);
        } catch (Exception e) {
            return;
        }


        String inputDateSatrt = DateUtils.prepareOutputDate(productData.getDate_start(), "yyyy-MM-dd HH:mm:ss", this);
        long diff_Will_Start = DateUtils.getDiff(inputDateSatrt, "yyyy-MM-dd HH:mm:ss");

        if (APP_DEBUG) {

            Log.e("_start_at_server", productData.getDate_start());
            Log.e("_start_at_device ", dateStartAt);
            Log.e("_start_at_diff ", String.valueOf(diff_Will_Start));
        }

        if (diff_Will_Start > 0) {

            if (productData.getIs_deal() == 1) {
                CountdownView mCvCountdownView = findViewById(R.id.cv_countdownViewTest1);


                mCvCountdownView.start(diff_Will_Start); // Millisecond
                dealLayout.setVisibility(View.VISIBLE);
            }

            productUpTo.setText(String.format(getString(R.string.product_start_at), dateStartAt));

        }


        String inputDateEnd = DateUtils.prepareOutputDate(productData.getDate_end(), "yyyy-MM-dd HH:mm:ss", this);
        long diff_will_end = DateUtils.getDiff(inputDateEnd, "yyyy-MM-dd HH:mm:ss");


        if (APP_DEBUG) {
            Log.e("_end_at_server", productData.getDate_end());
            Log.e("_end_at_device ", dateEndAt);
            Log.e("_end_at_diff ", String.valueOf(diff_will_end));
        }

        if (diff_will_end > 0 && diff_Will_Start < 0) {


            if (productData.getIs_deal() == 1) {
                CountdownView mCvCountdownView = findViewById(R.id.cv_countdownViewTest1);
                mCvCountdownView.start(diff_will_end); // Millisecond
                dealLayout.setVisibility(View.VISIBLE);

            }

            productUpTo.setText(String.format(getString(R.string.product_end_at), dateEndAt));

        }


        if (diff_Will_Start < 0 && diff_will_end < 0) {
            productUpTo.setText(String.format(getString(R.string.product_ended_at), dateEndAt));
        }


    }


    public void setupToolbar() {

        setupToolbar(toolbar);

        toolbar_back.setVisibility(View.GONE);
        toolbar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }


    public void getProduct(final int product_id) {

        mViewManager.loading();

        final GPStracker mGPS = new GPStracker(this);

        SimpleRequest request = new SimpleRequest(Request.Method.POST,
                Constances.API.API_GET_PRODUCTS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                mViewManager.showResult();


                try {

                    if (APP_DEBUG) {
                        Log.e("responseProductsString", response);
                    }

                    JSONObject jsonObject = new JSONObject(response);
                    final ProductParser mProductParser = new ProductParser(jsonObject);
                    RealmList<Product> list = mProductParser.getProducts();

                    if (list.size() > 0) {

                        ProductsController.insertProducts(list);

                        productData = list.get(0);
                        setupViews();

                    } else {

                        NSToast.show(getString(R.string.store_not_found));
                        finish();

                    }

                } catch (JSONException e) {
                    //send a rapport to support
                    if (APP_DEBUG)
                        e.printStackTrace();

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (APP_DEBUG) {
                    Log.e("ERROR", error.toString());
                }
                mViewManager.error();

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                if (mGPS.canGetLocation()) {
                    params.put("lat", mGPS.getLatitude() + "");
                    params.put("lng", mGPS.getLongitude() + "");
                }

                params.put("limit", "1");
                params.put("product_id", product_id + "");

                if (APP_DEBUG) {
                    Log.e("ProductDetail", "  params getProducts :" + params.toString());
                }

                return params;
            }

        };


        request.setRetryPolicy(new DefaultRetryPolicy(SimpleRequest.TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        VolleySingleton.getInstance(this).getRequestQueue().add(request);

    }


    @Override
    public void customErrorView(View v) {

    }

    @Override
    public void customLoadingView(View v) {

    }

    @Override
    public void customEmptyView(View v) {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (android.R.id.home == item.getItemId()) {
            if (!MainActivity.isOpend()) {
                startActivity(new Intent(this, MainActivity.class));
            }
            finish();
        }

        if (item.getItemId() == R.id.share) {
            {
                @SuppressLint({"StringFormatInvalid", "LocalSuppress", "StringFormatMatches"}) String shared_text =
                        String.format(getString(R.string.shared_text),
                                productData.getName(),
                                getString(R.string.app_name),
                                productData.getLink()
                        );


                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, shared_text);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);

            }
        }else if (item.getItemId() == R.id.report_icon) {

            if (!SessionsController.isLogged()) {
                startActivity(new Intent(ProductDetailActivity.this, LoginV2Activity.class));
                
            } else {

                Intent intent = new Intent(ProductDetailActivity.this, ReportIssueActivity.class);
                intent.putExtra("id", productData.getId());
                intent.putExtra("owner_id", productData.getUser_id());
                intent.putExtra("name", productData.getName());
                intent.putExtra("link", productData.getLink());
                intent.putExtra("module", "store");
                startActivity(intent);
            }


        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {

        if (!MainActivity.isOpend()) {
            startActivity(new Intent(this, MainActivity.class));
        } else {

        }

        super.onBackPressed();
    }


    private void showBottomSheetDialog(Cart mCart) {


        FrameLayout bottom_sheet = findViewById(R.id.bottom_sheet);
        bottom_sheet.setVisibility(View.VISIBLE);

        final BottomSheetBehavior[] mBehavior = {BottomSheetBehavior.from(bottom_sheet)};

        final BottomSheetDialog[] mBottomSheetDialog = {new BottomSheetDialog(this)};


        if (mBehavior[0].getState() == BottomSheetBehavior.STATE_EXPANDED) {
            mBehavior[0].setState(BottomSheetBehavior.STATE_COLLAPSED);
        }

        final View[] view = {getLayoutInflater().inflate(R.layout.order_quantity_sheet, null)};

        if (productData != null) {

            //set default  values
            if (productData.getProduct_type().equalsIgnoreCase("Price") && productData.getProduct_value() != 0) {
                custom_price = original_price = productData.getProduct_value();
                custom_qte = 1;
            }

            //set product_id image
            if (productData.getImages() != null) {
                Glide.with(AppController.getInstance())
                        .load(productData.getImages().getUrl200_200())
                        .centerCrop()
                        .placeholder(ImageLoaderAnimation.glideLoader(this))

                        .centerCrop().into(((ImageView) view[0].findViewById(R.id.image_product)));
                //set product_id name
                ((TextView) view[0].findViewById(R.id.product_name)).setText(productData.getName());

                //set product_id price
                parseProductValue(view[0].findViewById(R.id.product_price), -1);

                //action qte buttons
                (view[0].findViewById(R.id.btn_less_qte)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (custom_qte <= 1) return;
                        custom_qte--;
                        if (original_price < custom_price) {
                            custom_price = custom_price - original_price;
                        }
                        //set custom quantity
                        ((TextView) view[0].findViewById(R.id.product_quantity)).setText(custom_qte + "");

                        //set custom price
                        parseProductValue(view[0].findViewById(R.id.product_price), custom_price);

                    }
                });

                (view[0].findViewById(R.id.btn_more_qte)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        custom_qte++;
                        custom_price = custom_price + original_price;

                        //set custom quantity
                        ((TextView) view[0].findViewById(R.id.product_quantity)).setText(custom_qte + "");

                        //set custom price
                        parseProductValue(view[0].findViewById(R.id.product_price), custom_price);

                    }
                });


            }


            (view[0].findViewById(R.id.bt_confirm)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent = new Intent(new Intent(ProductDetailActivity.this, ProductCartActivity.class));

                    mCart.setQte(custom_qte);

                    //save cart in the database
                    CartController.addProductToCard(mCart);

                    intent.putExtra("module_id", productData.getId());
                    intent.putExtra("module", Constances.ModulesConfig.PRODUCT_MODULE);

                    startActivity(intent);
                    
                    finish();


                    mBottomSheetDialog[0].dismiss();

                }
            });

            (view[0].findViewById(R.id.btn_add_to_cart)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    mCart.setQte(custom_qte);
                    //save cart in the database
                    if (CartController.addProductToCard(mCart))
                        NSToast.show(getString(R.string.sucess_add_to_cart));

                    mBottomSheetDialog[0].dismiss();


                    //return to the previous page
                    onBackPressed();


                }
            });

            mBottomSheetDialog[0].setContentView(view[0]);
            mBottomSheetDialog[0].getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            mBottomSheetDialog[0].show();
            mBottomSheetDialog[0].setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    mBottomSheetDialog[0] = null;
                }

            });
        }

    }


    public void syncStoreFromAPI(final int store_id) {

        RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();

        SimpleRequest request = new SimpleRequest(Request.Method.POST,
                Constances.API.API_USER_GET_STORES, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);

                    final StoreParser mStoreParser = new StoreParser(jsonObject);
                    RealmList<Store> list = mStoreParser.getStore();

                    if (list.size() > 0) {
                        relatedStore = list.get(0);
                    }
                } catch (JSONException e) {
                    //send a rapport to support
                    e.printStackTrace();

                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (APP_DEBUG) {
                    Log.e("ERROR", error.toString());
                }
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                //
                params.put("limit", "1");
                params.put("store_id", String.valueOf(store_id));


                return params;
            }

        };


        request.setRetryPolicy(new DefaultRetryPolicy(SimpleRequest.TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        queue.add(request);

    }



    private void relatedProducts() {

        ProductCustomView mProductCustomView = findViewById(R.id.relatedProducts);
        if (!SettingsController.isModuleEnabled(Constances.ModulesConfig.PRODUCT_MODULE)) {
            mProductCustomView.hide();
        } else {
            HashMap<String, Object> optionalParams = new HashMap<>();

            optionalParams.put("is_featured", -1);
            optionalParams.put("order_by", "recent");
            optionalParams.put("category_id", productData.getCategory_id());
            optionalParams.put("displayHeader", true);
            optionalParams.put("header", getString(R.string.related_products));
            mProductCustomView.loadData(false, optionalParams);
            mProductCustomView.show();
            mProductCustomView.showHeader(getString(R.string.related_products));

            mProductCustomView.optionalParams.put("header",String.format(getString(R.string.related_products_to_category),productData.getCategories().get(0).getNameCat() ));
        }
    }

    private void bookMarkToggle(){
        if (!SessionsController.isLogged()) {
            startActivity(new Intent(ProductDetailActivity.this, LoginV2Activity.class));
            return;
        }
        try {
            User currentUser = SessionsController.getSession().getUser();
            if (productData.getSaved() > 0) {
                removeToBookmarks(this, currentUser.getId(), productData.getId());
            } else {
                saveToBookmarks(this, currentUser.getId(), productData.getId());
            }
        } catch (Exception e) {
            //send a rapport to support
            if (AppConfig.APP_DEBUG) e.printStackTrace();
        }
    }

    public void removeToBookmarks(final Context context, final int user_id, final int int_id) {

        ApiRequest.newPostInstance(Constances.API.API_PRODUCT_REMOVE, new ApiRequestListeners() {
            @Override
            public void onSuccess(Parser parser) {
                if (parser.getSuccess() == 1) {
                    productData = ProductsController.doSave(productData.getId(), 0);
                    setBookmarkIcons();
                } else {
                    NSToast.show(getString(R.string.something_went_wrong));
                }
            }

            @Override
            public void onFail(Map<String, String> errors) {

            }
        }, Map.of(
                "user_id", String.valueOf(user_id),
                "product_id", String.valueOf(int_id)
        ));
    }

    public void saveToBookmarks(final Context context, final int user_id, final int int_id) {

        ApiRequest.newPostInstance(Constances.API.API_PRODUCT_SAVE, new ApiRequestListeners() {
            @Override
            public void onSuccess(Parser parser) {
                if (parser.getSuccess() == 1) {
                    productData = ProductsController.doSave(productData.getId(), 1);
                    setBookmarkIcons();
                } else {
                    NSToast.show(getString(R.string.something_went_wrong));
                }
            }

            @Override
            public void onFail(Map<String, String> errors) {

            }
        }, Map.of(
                "user_id", String.valueOf(user_id),
                "product_id", String.valueOf(int_id)
        ));


    }

    @Override
    public void onScroll(int scrollY, float height) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }

        if (scrollY < (height / 3)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                menuContext.findItem(R.id.report_icon).setIconTintList(ContextCompat.getColorStateList(getApplicationContext(), android.R.color.white));
                menuContext.findItem(R.id.share).setIconTintList(ContextCompat.getColorStateList(getApplicationContext(), android.R.color.white));
            }
            final Drawable upArrow = ResourcesCompat.getDrawable(getResources(),R.drawable.back,null);
            upArrow.setColorFilter(ResourcesCompat.getColor(getResources(),R.color.white,null) , PorterDuff.Mode.SRC_ATOP) ;
            getSupportActionBar().setHomeAsUpIndicator(upArrow);

        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                menuContext.findItem(R.id.report_icon).setIconTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.color_toolbar_action));
                menuContext.findItem(R.id.share).setIconTintList(ContextCompat.getColorStateList(getApplicationContext(), R.color.color_toolbar_action));
            }
            final Drawable upArrow = getResources().getDrawable(R.drawable.back);
            upArrow.setColorFilter(ResourcesCompat.getColor(getResources(),R.color.color_toolbar_action,null) , PorterDuff.Mode.SRC_ATOP) ;
            getSupportActionBar().setHomeAsUpIndicator(upArrow);
        }

    }
}
