package ch.pizzapp.android.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.ButterKnife;
import ch.pizzapp.android.R;
import ch.pizzapp.android.adapter.recycler.NavigationMenuRecyclerAdapter;
import ch.pizzapp.android.fragment.CartFragment;
import ch.pizzapp.android.fragment.OrderHistoryFragment;
import ch.pizzapp.android.fragment.StoreInfoFragment;
import ch.pizzapp.android.fragment.MenuFragment;
import ch.pizzapp.android.fragment.ProductFragment;
import ch.pizzapp.android.fragment.ProfileFragment;
import ch.pizzapp.android.helper.DialogHelper;
import ch.pizzapp.android.helper.PriceHelper;
import ch.pizzapp.android.helper.SessionHelper;
import ch.pizzapp.android.helper.SharedPrefsHelper;
import ch.pizzapp.android.model.CategoryModel;
import ch.pizzapp.android.view.AppToolbar;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection;

public class MainActivity extends BaseActivity {

    @BindView(R.id.drawerLayout) DrawerLayout drawerLayout;
    @BindView(R.id.navigationMenuRecyclerView) RecyclerView navigationMenuRecyclerView;
    @BindView(R.id.pizzalinkToolbar) AppToolbar appToolbar;
    @BindView(R.id.cartTotalRelativeLayout) RelativeLayout cartTotalRelativeLayout;
    @BindView(R.id.cartTotalTextView) TextView cartTotalTextView;
    @BindView(R.id.bottomNavigationView) BottomNavigationViewEx bottomNavigationView;

    @BindView(R.id.badgeLayout) RelativeLayout badgeLayout;
    @BindView(R.id.badgeTextView) TextView badgeTextView;

    @BindView(R.id.shoppingCartButtonLayout) RelativeLayout shoppingCartButtonLayout;
    @BindView(R.id.shoppingCartImageView) ImageView shoppingCartImageView;
    @BindView(R.id.shoppingCartTextView) TextView shoppingCartTextView;

    @BindDrawable(R.drawable.ic_bottom_nav_item_cart_white) Drawable whiteCartDrawable;
    @BindDrawable(R.drawable.ic_bottom_nav_item_cart_red) Drawable redCartDrawable;

    @BindColor(R.color.red) int redColor;
    @BindColor(R.color.white) int whiteColor;

    private FragmentManager fragmentManager;
    private String currentFragmentName = "";
    private int currentCategoryId = -1;
    private boolean isStartWithOrderHistory;
    private ArrayList<CategoryModel> categoryList = new ArrayList<>();
    private NavigationMenuRecyclerAdapter navigationMenuRecyclerAdapter;
    //private Badge badge;
    private Animation animUp,animDown;

    private SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        getDataFromIntent();
        initViews();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

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

    private void getDataFromIntent(){
        isStartWithOrderHistory = getIntent().getBooleanExtra("isStartWithOrderHistory", false);
    }

    private void initViews(){
        //initBadgeView();
        initNavigationDrawer();
        initBottomNavigationView();
        showStartScreen();
        setCartItemCount();
        initShoppingCartButton();

    }

    private void initShoppingCartButton(){

        animDown = AnimationUtils.loadAnimation(this, R.anim.anim_scale_down);
        animUp = AnimationUtils.loadAnimation(this, R.anim.anim_scale_up);

        shoppingCartButtonLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case (android.view.MotionEvent.ACTION_DOWN):
                        shoppingCartButtonLayout.startAnimation(animDown);
                        return false;
                    case (android.view.MotionEvent.ACTION_UP):
                        shoppingCartButtonLayout.startAnimation(animUp);
                        return false;
                    case (android.view.MotionEvent.ACTION_CANCEL):
                        shoppingCartButtonLayout.startAnimation(animUp);
                }
                return false;
            }
        });

        shoppingCartButtonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!SessionHelper.isCustomerLoggedIn()){
                    DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                    return;
                }
                bottomNavigationView.setCurrentItem(2);
            }
        });
    }

    /*
    private void initBadgeView(){
        badge = new QBadgeView(this)
                .setBadgeBackgroundColor(redColor)
                .setBadgeTextColor(whiteColor)
                .setBadgeGravity(Gravity.TOP | Gravity.END);
    }
    */

    private void showStartScreen(){
        fragmentManager = getSupportFragmentManager();
        if(isStartWithOrderHistory){
            bottomNavigationView.setCurrentItem(1);
        }
        else {
            openProductsScreen(categoryList.get(3));
        }
    }
    private void initBottomNavigationView(){

        //bottomNavigationView.enableAnimation(false);
        bottomNavigationView.enableShiftingMode(false);
        bottomNavigationView.setTextSize(10);
        bottomNavigationView.enableItemShiftingMode(false);
        bottomNavigationView.setTextVisibility(true);
        bottomNavigationView.setIconSize(24, 24);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.action_menu:
                        if (currentFragmentName.equals(MenuFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer,
                                MenuFragment.newInstance(categoryList.get(3))).commit();
                        currentFragmentName = MenuFragment.FRAGMENT_NAME;

                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        if(!SharedPrefsHelper.getCartTotalPrice().equals("0") &&
                                !SharedPrefsHelper.getCartTotalPrice().equals("0.0") &&
                                !SharedPrefsHelper.getCartTotalPrice().equals("0.00")){
                            cartTotalTextView.setText(PriceHelper.getPriceWithCurreny(SharedPrefsHelper.getCartTotalPrice()));
                            cartTotalRelativeLayout.setVisibility(View.VISIBLE);
                        }

                        return true;

                    case R.id.action_empty:
                        if(!SessionHelper.isCustomerLoggedIn()){
                            DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                            return false;
                        }
                        if (currentFragmentName.equals(CartFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, CartFragment.newInstance()).commit();
                        currentFragmentName = CartFragment.FRAGMENT_NAME;

                        currentCategoryId = -1;

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(redCartDrawable);
                        shoppingCartTextView.setTextColor(redColor);

                        return true;

                    case R.id.action_history:
                        if(!SessionHelper.isCustomerLoggedIn()){
                            DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                            return false;
                        }
                        if (currentFragmentName.equals(OrderHistoryFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, OrderHistoryFragment.newInstance()).commit();
                        currentFragmentName = OrderHistoryFragment.FRAGMENT_NAME;

                        currentCategoryId = -1;

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        return true;

                    case R.id.action_profile:
                        if(!SessionHelper.isCustomerLoggedIn()){
                            DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                            return false;
                        }
                        if (currentFragmentName.equals(ProfileFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, ProfileFragment.newInstance()).commit();
                        currentFragmentName = ProfileFragment.FRAGMENT_NAME;

                        currentCategoryId = -1;

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        return true;

                    case R.id.action_info:
                        if (currentFragmentName.equals(StoreInfoFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, StoreInfoFragment.newInstance()).commit();
                        currentFragmentName = StoreInfoFragment.FRAGMENT_NAME;

                        currentCategoryId = -1;

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        return true;
                }
                return false;
            }
        });
    }

    private void initNavigationDrawer(){

        initNavigationMenuRecyclerView();

        appToolbar.getHamburgerIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(drawerLayout.isDrawerOpen(GravityCompat.START))
                    drawerLayout.closeDrawers();
                else
                    openNavigationDrawer();
            }
        });
    }

    private void openNavigationDrawer(){
        drawerLayout.openDrawer(GravityCompat.START);
    }

    public void setPizzalinkToolbarFields(boolean showHamburgerIcon, String title){
        appToolbar.setHamburgerIconVisibility(showHamburgerIcon);
        appToolbar.setTitle(title);
        if(showHamburgerIcon)
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        else
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    private void initNavigationMenuRecyclerView(){
        categoryList = SharedPrefsHelper.readCategoryList();

        for(int i = 0; i < categoryList.size(); i++){
            List<CategoryModel> subcategoryList = categoryList.get(i).getSubCategoryList();
            sectionAdapter.addSection(new CategorySection(i, categoryList.get(i).getName(), subcategoryList));
        }

        navigationMenuRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        navigationMenuRecyclerView.setAdapter(sectionAdapter);
    }

    private class CategorySection extends StatelessSection {

        String title;
        List<CategoryModel> list;
        int pstn;

        CategorySection(int pstn, String title, List<CategoryModel> list) {
            super(new SectionParameters.Builder(R.layout.row_subcategory)
                    .headerResourceId(R.layout.row_category)
                    .build());

            this.title = title;
            this.list = list;
            this.pstn = pstn;
        }

        private class HeaderViewHolder extends RecyclerView.ViewHolder {
            private final View rootView;
            private final TextView categoryNameItem;
            private final View bottomLineView;

            HeaderViewHolder(View view) {
                super(view);
                rootView = view;
                categoryNameItem = (TextView) view.findViewById(R.id.categoryNameItem);
                bottomLineView = view.findViewById(R.id.bottomLineView);
            }
        }

        private class ItemViewHolder extends RecyclerView.ViewHolder {

            private final View rootView;
            private final TextView subcategoryNameItem;
            private final View bottomLineView;

            ItemViewHolder(View view) {
                super(view);
                rootView = view;
                subcategoryNameItem = (TextView) view.findViewById(R.id.subcategoryNameItem);
                bottomLineView = (View) view.findViewById(R.id.bottomLineView);
            }
        }

        @Override
        public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
            return new HeaderViewHolder(view);
        }

        @Override
        public RecyclerView.ViewHolder getItemViewHolder(View view) {
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
            final HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
            headerHolder.categoryNameItem.setText(title);

            headerHolder.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openProductsScreen(categoryList.get(pstn));
                }
            });

            if(pstn == categoryList.size() - 1){
                headerHolder.bottomLineView.setVisibility(View.GONE);
                return;
            }

            if(categoryList.get(pstn).getSubCategoryList() == null ||
                    categoryList.get(pstn).getSubCategoryList().size() == 0){
                headerHolder.bottomLineView.setVisibility(View.VISIBLE);
            }else {
                headerHolder.bottomLineView.setVisibility(View.GONE);
            }

        }

        @Override
        public void onBindItemViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final ItemViewHolder itemHolder = (ItemViewHolder) holder;
            String name = list.get(position).getName();
            itemHolder.subcategoryNameItem.setText(name);
            if(position == list.size() - 1){
                itemHolder.bottomLineView.setVisibility(View.VISIBLE);
            }
            else {
                itemHolder.bottomLineView.setVisibility(View.GONE);
            }
            itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openProductsScreen(list.get(position));
                }
            });
        }

        @Override
        public int getContentItemsTotal() {
            return list.size();
        }
    }

    private void openProductsScreen(CategoryModel clickedCategoryModel){

        drawerLayout.closeDrawers();

        if(clickedCategoryModel.isProduct()){

            if(currentFragmentName.equals(ProductFragment.FRAGMENT_NAME) &&
                    currentCategoryId == clickedCategoryModel.getId())
                return;

            fragmentManager.beginTransaction().replace(R.id.fragmentContainer,
                    ProductFragment.newInstance(clickedCategoryModel)).commit();
            currentFragmentName = ProductFragment.FRAGMENT_NAME;
            currentCategoryId = clickedCategoryModel.getId();
        }
        else {

            if(currentFragmentName.equals(MenuFragment.FRAGMENT_NAME) &&
                    currentCategoryId == clickedCategoryModel.getId())
                return;


            fragmentManager.beginTransaction().replace(R.id.fragmentContainer,
                    MenuFragment.newInstance(clickedCategoryModel)).commit();
            currentFragmentName = MenuFragment.FRAGMENT_NAME;
            currentCategoryId = clickedCategoryModel.getId();
        }

    }

    public void setCartItemCount(){
        addBadgeAt(2, SharedPrefsHelper.getCartItemCount());
    }

    public void reopenCartFragment(){
        currentFragmentName = "";
        bottomNavigationView.setCurrentItem(2);
    }

    /*
    private void addBadgeAt(int position, int number) {
        badge.setBadgeNumber(number);
        badge.bindTarget(bottomNavigationView.getBottomNavigationItemView(position));
    }
    */

    private void addBadgeAt(int position, int number) {

        badgeTextView.setText(String.valueOf(number));

        if(number <= 0){
            badgeLayout.setVisibility(View.GONE);
        }
        else {
            badgeLayout.setVisibility(View.VISIBLE);
        }

        if(SharedPrefsHelper.getCartTotalPrice().equals("0") ||
                SharedPrefsHelper.getCartTotalPrice().equals("0.0") ||
                SharedPrefsHelper.getCartTotalPrice().equals("0.00")){
            cartTotalRelativeLayout.setVisibility(View.GONE);
        }
        else {
            cartTotalTextView.setText(PriceHelper.getPriceWithCurreny(SharedPrefsHelper.getCartTotalPrice()));
            cartTotalRelativeLayout.setVisibility(View.VISIBLE);
        }

    }

}
