package cpm.com.gskmtorange.dailyentry;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.preference.PreferenceManager;

import android.os.Bundle;

import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.adapter.ListAdapter;
import cpm.com.gskmtorange.adapter.MyAdapter;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.gsk_dailyentry.Stock_FacingActivity;
import cpm.com.gskmtorange.listener.Listener;
import cpm.com.gskmtorange.xmlGetterSetter.BrandMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.DynamycIdsGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MAPPING_PLANOGRAM_DataGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.NoCameraDataGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.RowColumnGetterSetter;

public class NoCameraActivity extends AppCompatActivity implements Listener {
    private Context context;
    GSKOrangeDB db;
    String store_id, visit_date, username, intime, date, keyAccount_id, class_id, storeType_id, camera_allow, str, country_id, store_flag_str;
    String categoryName, categoryId;
    int number_of_rows, FROM;
    private SharedPreferences preferences;
    LinearLayout linear_bottom_parent;
    ArrayList<DynamycIdsGetterSetter> ids = new ArrayList<>();

    ArrayList<NoCameraDataGetterSetter> top_list = new ArrayList<>();

    RecyclerView rvTop;
    MSL_AvailabilityStockFacingGetterSetter sub_category_data;

    FloatingActionButton fab, fab_add;

    ScrollView scroll_no_camera;

    int mScrollDistance = 0;

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

        setContentView(R.layout.activity_no_camera);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab_add = (FloatingActionButton) findViewById(R.id.fab_add);

        rvTop = (RecyclerView) findViewById(R.id.rvTop);
        linear_bottom_parent = (LinearLayout) findViewById(R.id.lin_bottom_parent);
        scroll_no_camera = (ScrollView) findViewById(R.id.scroll_no_camera);

        //SCROLLVIEW
        scroll_no_camera.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                mScrollDistance = scroll_no_camera.getScrollY(); // For ScrollView
                // DO SOMETHING WITH THE SCROLL COORDINATES
            }
        });

        //preference data
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        username = preferences.getString(CommonString.KEY_USERNAME, null);
        storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");
        class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
        store_flag_str = preferences.getString(CommonString.KEY_STORE_FLAG, null);

        str = CommonString.getImagesFolder(context);

        //Intent data
        categoryName = getIntent().getStringExtra("categoryName");
        categoryId = getIntent().getStringExtra("categoryId");
        number_of_rows = getIntent().getIntExtra(CommonString.KEY_NUMBER_OF_ROWS, 0);
        FROM = getIntent().getIntExtra(CommonString.KEY_FROM, 0);
        sub_category_data = (MSL_AvailabilityStockFacingGetterSetter) getIntent().getSerializableExtra(CommonString.KEY_SUB_CATEGORY);

        db = new GSKOrangeDB(NoCameraActivity.this);
        db.open();

        top_list = prepareTopList(categoryId);

        rvTop.setLayoutManager(new GridLayoutManager(this, 3));
        ListAdapter topListAdapter = new ListAdapter(top_list, this);
        rvTop.setAdapter(topListAdapter);
        //tvEmptyListTop.setOnDragListener(topListAdapter.getDragInstance());
        rvTop.setOnDragListener(topListAdapter.getDragInstance());

        if (FROM == 1) {
            String table_name = "NO_CAMERA_FACING_DATA";
            ArrayList<RowColumnGetterSetter> rows_data = db.getrowColumnNoCamera(store_id, categoryId, sub_category_data.getSub_category_id(), table_name);
            number_of_rows = rows_data.size();
            if(number_of_rows==0){
                table_name = "NO_CAMERA_LAST_VISIT_DATA";
                rows_data = db.getrowColumnNoCamera(store_id, categoryId, sub_category_data.getSub_category_id(), table_name);
                number_of_rows = rows_data.size();
            }

            for (int i = 1; i <= rows_data.size(); i++) {

                DynamycIdsGetterSetter dynamic_ids = new DynamycIdsGetterSetter();

                // first Button
                RelativeLayout rLayout = new RelativeLayout(context);
                RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                TextView tv = new TextView(context);
                tv.setHeight(60);
                tv.setTextSize(18);
                tv.setBackgroundColor(getResources().getColor(R.color.grey_textview));
                tv.setText("Drop SKU Groups Here ");
                tv.setPadding(5, 5, 0, 0);
                tv.setLayoutParams(lprams);
                int tv_id = View.generateViewId();
                tv.setId(tv_id);

                //set dynamic textview id to object
                dynamic_ids.setTextview_id(tv_id);

                RecyclerView rec_bottom = new RecyclerView(context);
                int rec_id = View.generateViewId();

                //set dynamic recycler id to object
                dynamic_ids.setRecycler_id(rec_id);

                rec_bottom.setLayoutParams(lprams);
                rec_bottom.setPadding(0, 0, 0, 0);

                rec_bottom.setVisibility(View.GONE);

                rec_bottom.setId(rec_id);
                rec_bottom.setBackgroundColor(getResources().getColor(R.color.grey_background));

                RelativeLayout.LayoutParams lprams2 = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                lprams2.height = 2;
                View view = new View(context);
                view.setBackgroundColor(getResources().getColor(R.color.white));
                view.setLayoutParams(lprams2);

                rLayout.addView(tv);
                rLayout.addView(rec_bottom);
                rLayout.addView(view);
                rLayout.setBackgroundColor(getResources().getColor(R.color.white));

                linear_bottom_parent.addView(rLayout);


                rec_bottom.setLayoutManager(new LinearLayoutManager(
                        this, LinearLayoutManager.HORIZONTAL, false));

                List<BrandMasterGetterSetter> bottomList = new ArrayList<>();

                List<NoCameraDataGetterSetter> sku_group_master = new ArrayList<>();

                for (int j = 1; j <= rows_data.get(i - 1).getColumn(); j++) {
                    NoCameraDataGetterSetter column_data = new NoCameraDataGetterSetter();
                    column_data = db.getRowSkuGroupCamera(store_id, categoryId, sub_category_data.getSub_category_id(), i, j, table_name);
                    sku_group_master.add(column_data);
                }

                dynamic_ids.setTotal_unit(getTotalUnit(sku_group_master));
                ids.add(dynamic_ids);

                MyAdapter adapter = new MyAdapter(context, sku_group_master, this, rec_bottom);
                rec_bottom.setAdapter(adapter);

                rec_bottom.scrollToPosition(sku_group_master.size() - 1);

                tv.setOnDragListener(adapter.getDragInstance());

                //delete row on LongClick
                tv.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View tvView) {
                       showDeleteDialog(tvView);
                        return false;
                    }
                });

                rec_bottom.setOnDragListener(adapter.getDragInstance());

                setEmptyListBottom(false, tv.getId(), rec_bottom);
            }

        } else {
            for (int i = 1; i <= number_of_rows; i++) {

                DynamycIdsGetterSetter dynamic_ids = new DynamycIdsGetterSetter();

                // first Button
                RelativeLayout rLayout = new RelativeLayout(context);
                RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                TextView tv = new TextView(context);
                //tv.setHeight(60);
                tv.setTextSize(20);
                tv.setBackgroundColor(getResources().getColor(R.color.grey_textview));
                tv.setText("Drop SKU Groups Here ");
                tv.setPadding(5, 20, 0, 20);
                tv.setLayoutParams(lprams);
                int tv_id = View.generateViewId();
                tv.setId(tv_id);

                //set dynamic textview id to object
                dynamic_ids.setTextview_id(tv_id);

                RecyclerView rec_bottom = new RecyclerView(context);
                int rec_id = View.generateViewId();

                //set dynamic recycler id to object
                dynamic_ids.setRecycler_id(rec_id);

                rec_bottom.setLayoutParams(lprams);
                rec_bottom.setPadding(0, 0, 0, 0);

                rec_bottom.setVisibility(View.GONE);

                rec_bottom.setId(rec_id);
                rec_bottom.setBackgroundColor(getResources().getColor(R.color.grey_background));

                RelativeLayout.LayoutParams lprams2 = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                lprams2.height = 2;
                View view = new View(context);
                view.setBackgroundColor(getResources().getColor(R.color.white));
                view.setLayoutParams(lprams2);

                rLayout.addView(tv);
                rLayout.addView(rec_bottom);
                rLayout.addView(view);
                rLayout.setBackgroundColor(getResources().getColor(R.color.white));

                linear_bottom_parent.addView(rLayout);

                ids.add(dynamic_ids);

                rec_bottom.setLayoutManager(new LinearLayoutManager(
                        this, LinearLayoutManager.HORIZONTAL, false));

                List<BrandMasterGetterSetter> bottomList = new ArrayList<>();

        /* bottomList.add("C");
        bottomList.add("D");*/

        /*setEmptyListBottom(true);
        ListAdapter bottomListAdapter = new ListAdapter(bottomList, this);
        rvBottom.setAdapter(bottomListAdapter);*/

                List<NoCameraDataGetterSetter> brands = new ArrayList<>();

                MyAdapter adapter = new MyAdapter(context, brands, this, rec_bottom);
                rec_bottom.setAdapter(adapter);

                tv.setOnDragListener(adapter.getDragInstance());

                //delete row on LongClick
                tv.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View tvView) {
                        showDeleteDialog(tvView);
                        return false;
                    }
                });


                rec_bottom.setOnDragListener(adapter.getDragInstance());

            }
        }


        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                boolean flag_all_rows_filled = true;
                String error_msg = "";

                HashMap<Integer, List<NoCameraDataGetterSetter>> hashMapRowData = new HashMap<>();

                for (int i = 0; i < number_of_rows; i++) {

                    int rec_id = ids.get(i).getRecycler_id();

                    RecyclerView target = (RecyclerView) findViewById(rec_id);
                    MyAdapter adapterMYTarget = (MyAdapter) target.getAdapter();
                    List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();
                    if (customListMyTarget.size() == 0) {
                        flag_all_rows_filled = false;
                        error_msg = getString(R.string.please_add_subgroup_facing);
                        break;
                    } else {
                        boolean flag_empty = true;
                        for (int k = 0; k < customListMyTarget.size(); k++) {
                            if (customListMyTarget.get(k).getSKUGROUP_ID().equals("-1")) {
                                flag_empty = false;
                                break;
                            }
                        }
                        if (flag_empty) {
                            hashMapRowData.put(i + 1, customListMyTarget);
                        } else {
                            flag_all_rows_filled = false;
                            error_msg = getString(R.string.please_add_subgroup_for_empty);
                            break;
                        }

                    }

                }

                if (flag_all_rows_filled) {
                    db.open();
                    db.InsertNoCameraAddedData(store_id, categoryId, sub_category_data.getSub_category_id(), number_of_rows, hashMapRowData);
                    finish();
                } else {
                    Snackbar.make(linear_bottom_parent, error_msg, Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        fab_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addRow();
            }
        });
    }

    private int getTotalUnit(List<NoCameraDataGetterSetter> sku_group_master) {
        int unit=0;
        for(int i=0; i<sku_group_master.size(); i++){
            unit = unit + getWidth(sku_group_master.get(i).isVertical(), sku_group_master.get(i).getFacing());
        }
        return unit;
    }

    public ArrayList<NoCameraDataGetterSetter> prepareTopList(String category_id) {

        return db.getSkuGroupMasterData(category_id, sub_category_data.getSub_category_id());
    }

    @Override
    public void setEmptyListBottom(boolean visibility, int tv, RecyclerView rv) {
        ((TextView) findViewById(tv)).setVisibility(visibility ? View.VISIBLE : View.GONE);
        rv.setVisibility(visibility ? View.GONE : View.VISIBLE);
    }

    @Override
    public void deleteItem(final View view, final int column_no, final RecyclerView rec, final NoCameraDataGetterSetter item) {

        final Dialog dialog = new Dialog(NoCameraActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.no_camera_edit_or_delete_dialog);

        final Button btn_edit = (Button) dialog.findViewById(R.id.btn_edit);
        final Button btn_delete = (Button) dialog.findViewById(R.id.btn_delete);

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

                final MyAdapter adapterMYTarget = (MyAdapter) rec.getAdapter();
                final List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();

                final Dialog dialog_facing = new Dialog(NoCameraActivity.this);
                dialog_facing.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog_facing.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog_facing.setContentView(R.layout.add_facing_custom_dialog);
                //pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
                //dialog.setCancelable(false);
                final EditText et_facing = (EditText) dialog_facing.findViewById(R.id.et_facing);

                final Button btn_ok = (Button) dialog_facing.findViewById(R.id.btn_ok);

                //final boolean isVertical = item.isVertical();

                final CheckBox vertical = (CheckBox)dialog_facing.findViewById(R.id.cb_vertical);
                final CheckBox horizontal =(CheckBox)dialog_facing.findViewById(R.id.cb_horizontal);

                if(item.isVertical()){
                    vertical.setChecked(true);
                }
                else {
                    horizontal.setChecked(true);
                }

                et_facing.setText(item.getFacing()+"");

                vertical.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (vertical.isChecked()) {
                            vertical.setChecked(true);
                            horizontal.setChecked(false);
                        }
                    }
                });

                horizontal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (horizontal.isChecked()) {
                            horizontal.setChecked(true);
                            vertical.setChecked(false);
                        }
                    }
                });

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

                        String facing = et_facing.getText().toString();
                        boolean isVertical = vertical.isChecked();

                        if (facing.equals("")) {
                            Snackbar.make(btn_ok, R.string.please_facing, Snackbar.LENGTH_SHORT).show();
                        } else {

                            DynamycIdsGetterSetter current_id = new DynamycIdsGetterSetter();

                            for (int i = 0; i < ids.size(); i++) {

                                if (ids.get(i).getRecycler_id() == rec.getId()) {
                                    current_id = ids.get(i);
                                    break;
                                }
                            }

                            boolean flag = true;
                            int facing_int = Integer.parseInt(facing);
                            int total_facing = 0;
                            int total_width = 0;

                            for (int i = 0; i < customListMyTarget.size(); i++) {

                                total_facing = total_facing + customListMyTarget.get(i).getFacing();
                                total_width = total_width + getWidth(customListMyTarget.get(i).isVertical(), customListMyTarget.get(i).getFacing());

                                if (customListMyTarget.get(i).getSKUGROUP_ID().equals("-1")) {
                                    int blank_width = getWidth(customListMyTarget.get(i).isVertical(),customListMyTarget.get(i).getFacing());
                                    int width = getWidth(isVertical,facing_int) - getWidth(customListMyTarget.get(column_no).isVertical(),customListMyTarget.get(column_no).getFacing());
                                    int remaining_width = blank_width - width;

                                    if(remaining_width>=0){

                                        if(remaining_width!=0){
                                            //set remaining width to blank icon
                                            customListMyTarget.get(i).setFacing(remaining_width/CommonString.UNIT_VERTICAL);
                                        }
                                        else {
                                            customListMyTarget.remove(i);
                                        }

                                        //set updated data to edited item
                                        customListMyTarget.get(column_no).setFacing(facing_int);
                                        customListMyTarget.get(column_no).setVertical(isVertical);

                                    }
                                    else {
                                        //current_id.setTotal_unit(current_id.getTotal_unit() - remaining_width);
                                        Snackbar.make(scroll_no_camera, R.string.invalid_facing, Snackbar.LENGTH_SHORT).show();
                                    }

                                    flag = false;
                                    break;
                                }
                                else {
                                    if (customListMyTarget.get(i).getSKUGROUP_ID().equals("21")) {
                                        int  access_width = getWidth(isVertical,facing_int) - getWidth(customListMyTarget.get(column_no).isVertical(),customListMyTarget.get(column_no).getFacing());

                                        if(access_width>0){
                                            Snackbar.make(scroll_no_camera, R.string.invalid_facing, Snackbar.LENGTH_SHORT).show();
                                        }
                                        else {
                                            if(access_width<0){
                                                NoCameraDataGetterSetter item = new NoCameraDataGetterSetter();
                                                item.setSKUGROUP_ID("-1");
                                                item.setSKUGROUP_NAME("");
                                                item.setFacing((-access_width)/CommonString.UNIT_VERTICAL);
                                                item.setVertical(true);

                                                customListMyTarget.add(i, item);
                                            }

                                            //set updated data to edited item
                                            customListMyTarget.get(column_no).setFacing(facing_int);
                                            customListMyTarget.get(column_no).setVertical(isVertical);
                                        }

                                        flag = false;
                                        break;
                                    }
                                }

                            }

                            if (flag) {

                                int width = getWidth(isVertical, facing_int);

                                current_id.setTotal_unit(current_id.getTotal_unit() - getWidth(item.isVertical(), item.getFacing()) + width);

                                customListMyTarget.get(column_no).setFacing(facing_int);
                                customListMyTarget.get(column_no).setVertical(isVertical);
                            }

                            adapterMYTarget.updateList(customListMyTarget);
                            adapterMYTarget.notifyDataSetChanged();
                            dialog_facing.cancel();
                        }

                    }
                });

                //dialog.setCancelable(false);
                dialog_facing.show();

                dialog.cancel();

            }
        });

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

                dialog.cancel();

                DynamycIdsGetterSetter current_id = new DynamycIdsGetterSetter();
                for (int i = 0; i < ids.size(); i++) {

                    if (ids.get(i).getRecycler_id() == rec.getId()) {
                        current_id = ids.get(i);
                        break;
                    }
                }

                //if Block separator is deleted every separator and Space is deleted in every row
                if (item.getSKUGROUP_ID().equals("21")) {
                    for (int i = 0; i < ids.size(); i++) {
                        RecyclerView rec = findViewById(ids.get(i).getRecycler_id());
                        MyAdapter adapterMYTarget = (MyAdapter) rec.getAdapter();
                        List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();

                        Iterator<NoCameraDataGetterSetter> iterator = customListMyTarget.iterator();
                        while (iterator.hasNext()) {
                            NoCameraDataGetterSetter item = iterator.next(); // must be called before you can call iterator.remove()
                            // Check condition
                            if (item.getSKUGROUP_ID().equals("-1")) {
                                iterator.remove();
                                ids.get(i).setTotal_unit(ids.get(i).getTotal_unit()- getWidth(item.isVertical(),item.getFacing()));
                            }
                            else if(item.getSKUGROUP_ID().equals("21")){
                                iterator.remove();
                                ids.get(i).setTotal_unit(ids.get(i).getTotal_unit()- getWidth(item.isVertical(),item.getFacing()));
                            }
                        }

                        adapterMYTarget.updateList(customListMyTarget);
                        adapterMYTarget.notifyDataSetChanged();

                        if (customListMyTarget.size() == 0) {

                            ((TextView) findViewById(ids.get(i).getTextview_id())).setVisibility(View.VISIBLE);
                            rec.setVisibility(View.GONE);
                        }
                    }
                } else {
                    MyAdapter adapterMYTarget = (MyAdapter) rec.getAdapter();

                    List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();

                    //if there are more items after deleted item
                    if (customListMyTarget.size() - 1 > column_no) {

                        boolean flag = true;
                        int index=0;
                        for (int l = column_no + 1; l < customListMyTarget.size(); l++) {
                            if (customListMyTarget.get(l).getSKUGROUP_ID().equals("-1")) {
                                flag = false;
                                customListMyTarget.get(l).setFacing(customListMyTarget.get(l).getFacing() + getWidth(item.isVertical(), item.getFacing())/CommonString.UNIT_VERTICAL);
                                break;
                            }
                            else if(customListMyTarget.get(l).getSKUGROUP_ID().equals("21")){
                                flag = false;

                                NoCameraDataGetterSetter new_item = new NoCameraDataGetterSetter();

                                int width = getWidth(item.isVertical(), item.getFacing());

                                new_item.setSKUGROUP_ID("-1");
                                new_item.setSKUGROUP_NAME("");
                                new_item.setFacing(width/CommonString.UNIT_VERTICAL);
                                new_item.setVertical(true);

                                customListMyTarget.add(l, new_item);

                                break;
                            }
                        }

                        customListMyTarget.remove(column_no);
                        if(flag){
                            current_id.setTotal_unit(current_id.getTotal_unit()- getWidth(item.isVertical(),item.getFacing()));
                        }

                    } else {
                        customListMyTarget.remove(column_no);
                        current_id.setTotal_unit(current_id.getTotal_unit()- getWidth(item.isVertical(),item.getFacing()));
                    }


                    adapterMYTarget.updateList(customListMyTarget);
                    adapterMYTarget.notifyDataSetChanged();
                    if (customListMyTarget.size() == 0) {

                        int view_id = rec.getId();
                        int tv_id = 0;
                        for (int i = 0; i < ids.size(); i++) {

                            if (ids.get(i).getRecycler_id() == view_id) {
                                tv_id = ids.get(i).getTextview_id();
                            }
                        }

                        if (tv_id != 0) {
                            ((TextView) findViewById(tv_id)).setVisibility(View.VISIBLE);
                            rec.setVisibility(View.GONE);
                        }
                    }
                }

            }
        });

        //dialog.setCancelable(false);
        dialog.show();

    }

    @Override
    public void addNUpdateRow(View v, int view_id, NoCameraDataGetterSetter parent_item) {

      /*  int rv_id = 0;
        if (v instanceof TextView) {

            for (int i = 0; i < ids.size(); i++) {

                if (ids.get(i).getTextview_id() == view_id) {
                    rv_id = ids.get(i).getRecycler_id();
                }
            }

            RecyclerView target = (RecyclerView) v.getRootView().findViewById(rv_id);
            ((TextView) findViewById(view_id)).setVisibility(false ? View.VISIBLE : View.GONE);
            target.setVisibility(false ? View.GONE : View.VISIBLE);

        } else {
            rv_id = view_id;
        }

        RecyclerView target;
        target = (RecyclerView) v.getRootView().findViewById(rv_id);

        MyAdapter adapterMYTarget = (MyAdapter) target.getAdapter();
        List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();*/


      //if it is valid for add
      if(isAddValid(parent_item, v, view_id)){
          showAddFacingDialog(parent_item, v, view_id);
      }


    }

    @Override
    public void smoothScrollToRow(View v, DragEvent event) {

        //no action necessary
        int y = Math.round(v.getY()) + Math.round(event.getY());
        int translatedY = y - mScrollDistance;
        //Log.i("translated",""+translatedY+" "+ mScrollDistance+" "+y);
        int threshold = 50;
        // make a scrolling up due the y has passed the threshold
       /* if (translatedY < 200) {
            // make a scroll up by 30 px
            scroll_no_camera.smoothScrollBy(0, -15);
        }
        // make a autoscrolling down due y has passed the 500 px border
        if (translatedY + threshold > 500) {
            // make a scroll down by 30 px
            scroll_no_camera.smoothScrollBy(0, 15);
        }*/
    }


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

        // return true so that the menu pop up is opened
        return true;
    }

    //public void showAddFacingDialog(final MyAdapter adapterMYTarget, final List<NoCameraDataGetterSetter> customListMyTarget, final NoCameraDataGetterSetter parent_item, final View view, final int view_id) {
    public void showAddFacingDialog(final NoCameraDataGetterSetter parent_item, final View view, final int view_id) {
        // ArrayList<SkuMasterGetterSetter> skuMasterGetterSetterArrayList = db.getSkuT2PData("1", "1", "1",)
        final Dialog dialog = new Dialog(NoCameraActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.add_facing_custom_dialog);
        //pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
        //dialog.setCancelable(false);
        final EditText et_facing = (EditText) dialog.findViewById(R.id.et_facing);

        final Button btn_ok = (Button) dialog.findViewById(R.id.btn_ok);

        final CheckBox vertical = (CheckBox)dialog.findViewById(R.id.cb_vertical);
        final CheckBox horizontal =(CheckBox)dialog.findViewById(R.id.cb_horizontal);
        final LinearLayout layout_placement = (LinearLayout) dialog.findViewById(R.id.lay_placement);
        horizontal.setChecked(true);

        vertical.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (vertical.isChecked()) {
                    vertical.setChecked(true);
                    horizontal.setChecked(false);
                }
            }
        });

        horizontal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (horizontal.isChecked()) {
                    horizontal.setChecked(true);
                    vertical.setChecked(false);
                }
            }
        });

        if(parent_item.getSKUGROUP_ID().equals("25")){
            layout_placement.setVisibility(View.GONE);
        }

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

                String facing = et_facing.getText().toString();
                boolean isVertical = vertical.isChecked();


                if (facing.equals("")) {
                    Snackbar.make(btn_ok, R.string.please_facing, Snackbar.LENGTH_SHORT).show();
                } else {

                    DynamycIdsGetterSetter current_id = new DynamycIdsGetterSetter();

                    int rv_id = 0;
                    if (view instanceof TextView) {

                        for (int i = 0; i < ids.size(); i++) {

                            if (ids.get(i).getTextview_id() == view_id) {
                                rv_id = ids.get(i).getRecycler_id();
                                current_id = ids.get(i);
                            }
                        }

                        RecyclerView target = (RecyclerView) view.getRootView().findViewById(rv_id);
                        ((TextView) findViewById(view_id)).setVisibility(false ? View.VISIBLE : View.GONE);
                        target.setVisibility(false ? View.GONE : View.VISIBLE);

                    } else {
                        rv_id = view_id;

                        for (int i = 0; i < ids.size(); i++) {

                            if (ids.get(i).getRecycler_id() == rv_id) {
                                current_id = ids.get(i);
                                break;
                            }
                        }
                    }

                    if (parent_item.getSKUGROUP_ID().equals("21")) {
                        //If Block Seperator is added

                        int max = 0;
                        HashMap<DynamycIdsGetterSetter, List<NoCameraDataGetterSetter>> biglistMap = new HashMap<>();
                        for (int i = 0; i < ids.size(); i++) {
                            RecyclerView target;
                            target = (RecyclerView) view.getRootView().findViewById(ids.get(i).getRecycler_id());

                            MyAdapter adapterMYTarget = (MyAdapter) target.getAdapter();
                            List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();
                            biglistMap.put(ids.get(i), customListMyTarget);
                           /* if (max < customListMyTarget.size()) {
                                max = customListMyTarget.size();
                            } */

                            if(customListMyTarget.size()>0 && !customListMyTarget.get(0).getSKUGROUP_ID().equals("25")){
                                if (max < ids.get(i).getTotal_unit()) {
                                    max = ids.get(i).getTotal_unit();
                                }
                            }


                        }

                        for (int i = 0; i < ids.size(); i++) {
                            List<NoCameraDataGetterSetter> customList = biglistMap.get(ids.get(i));

                            if(customList.size()>0 && customList.get(0).getSKUGROUP_ID().equals("25")){

                            }
                            else{

                                //if (customList.size() < max) {
                                if (ids.get(i).getTotal_unit() < max) {
                                    //int count = max - customList.size();
                                    int count = max - ids.get(i).getTotal_unit();

                                /*for (int j = 0; j < count; j++) {

                                    NoCameraDataGetterSetter item = new NoCameraDataGetterSetter();
                                    item.setSKUGROUP_ID("-1");
                                    item.setSKUGROUP_NAME("");
                                    item.setFacing(0);
                                    customList.add(item);
                                }*/

                                    NoCameraDataGetterSetter item = new NoCameraDataGetterSetter();
                                    item.setSKUGROUP_ID("-1");
                                    item.setSKUGROUP_NAME("");
                                    item.setFacing(count/CommonString.UNIT_VERTICAL);
                                    item.setVertical(true);
                                    customList.add(item);

                                    ids.get(i).setTotal_unit(ids.get(i).getTotal_unit() + count);

                                }
                                int facing_int = Integer.parseInt(facing);
                                parent_item.setFacing(facing_int);
                                NoCameraDataGetterSetter item = new NoCameraDataGetterSetter();
                                item.setSKUGROUP_ID(parent_item.getSKUGROUP_ID());
                                item.setSKUGROUP_NAME(parent_item.getSKUGROUP_NAME());
                                item.setFacing(facing_int);
                                item.setVertical(isVertical);
                                customList.add(item);
                                int width;
                                if(isVertical){
                                    width = facing_int* CommonString.UNIT_VERTICAL;
                                }
                                else {
                                    width = facing_int* CommonString.UNIT_HORIZONTAL;
                                }
                                ids.get(i).setTotal_unit(ids.get(i).getTotal_unit() + width);

                                RecyclerView target = (RecyclerView) view.getRootView().findViewById(rv_id);

                                MyAdapter adapterMYTarget = (MyAdapter) target.getAdapter();

                                adapterMYTarget.notifyDataSetChanged();

                                target.scrollToPosition(customList.size() - 1);

                                ((TextView) findViewById(ids.get(i).getTextview_id())).setVisibility(View.GONE);
                                ((RecyclerView) findViewById(ids.get(i).getRecycler_id())).setVisibility(View.VISIBLE);
                            }
                        }

                    } else{

                        RecyclerView target;
                        target = (RecyclerView) view.getRootView().findViewById(rv_id);

                        MyAdapter adapterMYTarget = (MyAdapter) target.getAdapter();
                        List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();

                        int facing_int = Integer.parseInt(facing);
                        parent_item.setFacing(facing_int);
                        NoCameraDataGetterSetter item = new NoCameraDataGetterSetter();
                        item.setSKUGROUP_ID(parent_item.getSKUGROUP_ID());
                        item.setSKUGROUP_NAME(parent_item.getSKUGROUP_NAME());
                        item.setFacing(facing_int);
                        item.setVertical(isVertical);
                        boolean flag = true;
                        for (int i = 0; i < customListMyTarget.size(); i++) {

                            if (customListMyTarget.get(i).getSKUGROUP_ID().equals("-1")) {
                                int facing_blank = customListMyTarget.get(i).getFacing();
                                int width = getWidth(isVertical, facing_int);
                                int remaining_width = facing_blank * CommonString.UNIT_VERTICAL - width;

                                if(remaining_width>=0){

                                    customListMyTarget.set(i, item);

                                    if(remaining_width!=0){
                                        NoCameraDataGetterSetter blank_item = new NoCameraDataGetterSetter();
                                        blank_item.setSKUGROUP_ID("-1");
                                        blank_item.setSKUGROUP_NAME("");
                                        blank_item.setFacing(remaining_width/CommonString.UNIT_VERTICAL);
                                        blank_item.setVertical(true);
                                        customListMyTarget.add(i+1 ,blank_item);
                                    }

                                }
                                else {
                                    //current_id.setTotal_unit(current_id.getTotal_unit() - remaining_width);
                                    Snackbar.make(scroll_no_camera, R.string.invalid_facing, Snackbar.LENGTH_SHORT).show();
                                }

                                flag = false;
                                break;
                            }
                        }

                        if (flag) {
                            customListMyTarget.add(item);

                            int width= getWidth(isVertical, facing_int);
                            current_id.setTotal_unit(current_id.getTotal_unit() + width);
                        }

                        adapterMYTarget.updateList(customListMyTarget);
                        adapterMYTarget.notifyDataSetChanged();
                        target.scrollToPosition(customListMyTarget.size() - 1);
                    }

                    dialog.cancel();
                }

            }
        });

        //dialog.setCancelable(false);
        dialog.show();

    }

    boolean isAddValid(final NoCameraDataGetterSetter parent_item, final View view, final int view_id){
        boolean flag = true;

        if (!(view instanceof TextView)) {
            RecyclerView target;
            target = (RecyclerView) view.getRootView().findViewById(view_id);

            MyAdapter adapterMYTarget = (MyAdapter) target.getAdapter();
            List<NoCameraDataGetterSetter> customListMyTarget = adapterMYTarget.getList();

            //if dropped item is Horizontal Separator
            if(parent_item.getSKUGROUP_ID().equals("25")){
                if(customListMyTarget.size()>0){
                    flag = false;
                    Snackbar.make(scroll_no_camera, R.string.cannot_add_horizontal_to_filled_row, Snackbar.LENGTH_SHORT).show();
                }
            }
            else {
                for (int i = 0; i < customListMyTarget.size(); i++) {
                    if(customListMyTarget.get(i).getSKUGROUP_ID().equals("25")){
                        Snackbar.make(scroll_no_camera, R.string.cannot_add_to_horizontal_seperatore, Snackbar.LENGTH_SHORT).show();

                        flag = false;
                        break;
                    }
                }
            }

        }

        return flag;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_planogram) {

            final Dialog dialog = new Dialog(NoCameraActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.setContentView(R.layout.planogram_dialog_layout);
            dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            dialog.setCancelable(false);

            ArrayList<MAPPING_PLANOGRAM_DataGetterSetter> mappingPlanogramList;


            if (country_id.equals("7")||country_id.equals("8")||country_id.equals("11")) {
                mappingPlanogramList= db.getMappingPlanogramData(categoryId, null, null, store_id, CommonString.TABLE_MAPPING_PLANOGRAM_STORE_WISE);
            } else if(store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
                mappingPlanogramList= db.getMappingPlanogramData(categoryId, storeType_id, class_id, null, CommonString.TABLE_MAPPING_PLANOGRAM_ADHOC);
            }
            else {
                mappingPlanogramList= db.getMappingPlanogramData(categoryId, storeType_id, class_id, null, CommonString.TABLE_MAPPING_PLANOGRAM);
            }

            //ImageView img_planogram = (ImageView) dialog.findViewById(R.id.img_planogram);
            WebView webView = (WebView) dialog.findViewById(R.id.webview);
            webView.setWebViewClient(new MyWebViewClient());

            webView.getSettings().setAllowFileAccess(true);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setBuiltInZoomControls(true);

            String planogram_image = "";
            if (mappingPlanogramList.size() > 0) {
                planogram_image = mappingPlanogramList.get(0).getPLANOGRAM_IMAGE();
            }
            if (!planogram_image.equals("")) {
                if (new File(CommonString.getDownloadedImageFolder(context) + planogram_image).exists()) {
                    Bitmap bmp = BitmapFactory.decodeFile(CommonString.getDownloadedImageFolder(context) + planogram_image);
                    // img_planogram.setRotation(90);
                    //img_planogram.setImageBitmap(bmp);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

                    String imagePath = "file://" + CommonString.getDownloadedImageFolder(context) + "/" + planogram_image;
                    String html = "<html><head></head><body><img src=\"" + imagePath + "\"></body></html>";
                    webView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");

                    dialog.show();
                } /*else {
                //webView.loadUrl(String.valueOf(R.drawable.sad_cloud));

                //img_planogram.setBackgroundResource(R.drawable.sad_cloud);
            }*/
            }


            ImageView cancel = (ImageView) dialog.findViewById(R.id.img_cancel);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    dialog.dismiss();
                }
            });
        }

        if (id == android.R.id.home) {

            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(NoCameraActivity.this);
            builder.setTitle("Parinaam");
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            finish();
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
            android.app.AlertDialog alert = builder.create();
            alert.show();

        }

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
         super.onBackPressed();

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(NoCameraActivity.this);
        builder.setTitle("Parinaam");
        builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }
                })
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        android.app.AlertDialog alert = builder.create();
        alert.show();
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.clearCache(true);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
    }

    int getWidth(boolean isVertical, int facing_int){
        int width;
        if(isVertical){
            width = facing_int* CommonString.UNIT_VERTICAL;
        }
        else {
            width = facing_int* CommonString.UNIT_HORIZONTAL;
        }
        return width;
    }

    void addRow(){
        DynamycIdsGetterSetter dynamic_ids = new DynamycIdsGetterSetter();
        // first Button
        RelativeLayout rLayout = new RelativeLayout(context);
        RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        TextView tv = new TextView(context);
        //tv.setHeight(60);
        tv.setTextSize(20);
        tv.setBackgroundColor(getResources().getColor(R.color.grey_textview));
        tv.setText("Drop SKU Groups Here ");
        tv.setPadding(5, 20, 0, 20);
        tv.setLayoutParams(lprams);
        int tv_id = View.generateViewId();
        tv.setId(tv_id);
        //set dynamic textview id to object
        dynamic_ids.setTextview_id(tv_id);
        RecyclerView rec_bottom = new RecyclerView(context);
        int rec_id = View.generateViewId();
        //set dynamic recycler id to object
        dynamic_ids.setRecycler_id(rec_id);
        rec_bottom.setLayoutParams(lprams);
        rec_bottom.setPadding(0, 0, 0, 0);
        rec_bottom.setVisibility(View.GONE);
        rec_bottom.setId(rec_id);
        rec_bottom.setBackgroundColor(getResources().getColor(R.color.grey_background));

        RelativeLayout.LayoutParams lprams2 = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lprams2.height = 2;
        View view = new View(context);
        view.setBackgroundColor(getResources().getColor(R.color.white));
        view.setLayoutParams(lprams2);

        rLayout.addView(tv);
        rLayout.addView(rec_bottom);
        rLayout.addView(view);
        rLayout.setBackgroundColor(getResources().getColor(R.color.white));

        linear_bottom_parent.addView(rLayout);

        ids.add(dynamic_ids);

        rec_bottom.setLayoutManager(new LinearLayoutManager(
                this, LinearLayoutManager.HORIZONTAL, false));

        List<BrandMasterGetterSetter> bottomList = new ArrayList<>();

        /* bottomList.add("C");
        bottomList.add("D");*/

        /*setEmptyListBottom(true);
        ListAdapter bottomListAdapter = new ListAdapter(bottomList, this);
        rvBottom.setAdapter(bottomListAdapter);*/

        List<NoCameraDataGetterSetter> brands = new ArrayList<>();

        MyAdapter adapter = new MyAdapter(context, brands, this, rec_bottom);
        rec_bottom.setAdapter(adapter);

        tv.setOnDragListener(adapter.getDragInstance());

        //delete row on LongClick
        tv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View tvView) {

                showDeleteDialog(tvView);

                return false;
            }
        });

        rec_bottom.setOnDragListener(adapter.getDragInstance());

        //increase No of rows
        number_of_rows++;
    }

    void showDeleteDialog(final View tvView){

        final Dialog dialog = new Dialog(NoCameraActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.delete_row_alert_dialog);

        final Button btn_no = (Button) dialog.findViewById(R.id.btn_no);
        final Button btn_yes = (Button) dialog.findViewById(R.id.btn_yes);

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

                int position = -1;

                for (int i = 0; i < ids.size(); i++) {

                    if (ids.get(i).getTextview_id() == tvView.getId()) {
                        position = i;
                        break;
                    }
                }

                if(position!=-1){
                    linear_bottom_parent.removeViewAt(position);
                    linear_bottom_parent.invalidate();

                    ids.remove(position);
                    --number_of_rows;
                }

                dialog.cancel();
            }
        });

        btn_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });

        dialog.show();
    }
}
