package in.techware.carrefour.activity;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

import in.techware.carrefour.R;
import in.techware.carrefour.activity.elie.ElieActivity;
import in.techware.carrefour.activity.info.ProductInfoActivity;
import in.techware.carrefour.activity.it.ITActivity;
import in.techware.carrefour.activity.it.WasteActivity;
import in.techware.carrefour.activity.merchandise.MerchandiseActivity;
import in.techware.carrefour.activity.order.OrderActivity;
import in.techware.carrefour.activity.receive.ReceiveActivity;
import in.techware.carrefour.adapters.MenuListRecyclerAdapter;
import in.techware.carrefour.config.Config;
import in.techware.carrefour.dialogs.ConfirmationDialog;
import in.techware.carrefour.model.MenuBean;
import in.techware.carrefour.util.AppConstants;
import in.techware.carrefour.util.menuUtils.HomeMenuUtil;
import in.techware.carrefour.viewModels.HomeViewModel;

public class HomeActivity extends BaseAppCompatNoDrawerActivity {

    private RecyclerView rvHome;
    Switch switchKeyboard;
    private MenuListRecyclerAdapter adapter;
    private ConfirmationDialog confirmationDialog;
    private HomeViewModel viewModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_home);

        /**
         * If menu items are dynamic
         */
        setContentView(R.layout.activity_home_with_list);

        viewModel = (HomeViewModel) ViewModelProviders.of(this).get(HomeViewModel.class);


        initViews();
        handleKeyboard();

//        swipeView.setPadding(0, 0, 0, 0);

        if (getSupportActionBar() != null) {
            setTitle(R.string.title_main_menu, R.color.white);
            getSupportActionBar().setTitle("");
            getSupportActionBar().setDisplayShowTitleEnabled(true);
        }
    }

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

        setProgressScreenVisibility(true, true);
        if (Config.getInstance().getAppSettingsBean() != null) {
            viewModel.setMenuListBean(HomeMenuUtil.getMenuList(Config.getInstance().getAppSettingsBean().getPDTFunction()));
            populateHomeMenu();
        } else {
            Config.getInstance().initAppSettings();
            if (Config.getInstance().getAppSettingsBean() != null) {
                viewModel.setMenuListBean(HomeMenuUtil.getMenuList(Config.getInstance().getAppSettingsBean().getPDTFunction()));
                populateHomeMenu();
            } else {
                viewModel.setMenuListBean(HomeMenuUtil.getMenuList("127"));
                populateHomeMenu();
            }
        }
        setDummyMenuVisibility(false);
    }

    private void initViews() {

        switchKeyboard = findViewById(R.id.switch_keyboard);

        rvHome = findViewById(R.id.rv_home);
        rvHome.setHasFixedSize(true);
        rvHome.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));

        switchKeyboard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switchKeyboard.setText(isChecked ? getResources().getString(in.techware.carrefour.R.string.keyboard_on_label)
                        : getResources().getString(in.techware.carrefour.R.string.keyboard_off_label));
                getSharedPreferences(AppConstants.PREF_FILE, 0)
                        .edit()
                        .putBoolean(AppConstants.KEYBOARD_STATUS, isChecked)
                        .apply();
            }
        });

        confirmationDialog = new ConfirmationDialog(this);
        confirmationDialog.setConfirmationDialogActionListener(new ConfirmationDialog.ConfirmationDialogActionListener() {
            @Override
            public void onYesClicked() {
                finishAffinity();
            }

            @Override
            public void onNoClicked() {

            }
        });
    }

    private void handleKeyboard() {
        if (getSharedPreferences(AppConstants.PREF_FILE, 0).getBoolean(AppConstants.KEYBOARD_STATUS, false)) {
            switchKeyboard.setText(getResources().getString(in.techware.carrefour.R.string.keyboard_on_label));
            switchKeyboard.setChecked(true);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        } else {
            switchKeyboard.setText(getResources().getString(in.techware.carrefour.R.string.keyboard_off_label));
            switchKeyboard.setChecked(false);
        }
    }

    private void populateHomeMenu() {

        if (adapter == null) {
            adapter = new MenuListRecyclerAdapter(this, viewModel.getMenuListBean());
            adapter.setMenuListRecyclerAdapterListener(new MenuListRecyclerAdapter.MenuListRecyclerAdapterListener() {
                @Override
                public void onMenuClicked(int position, MenuBean menuBean) {

                    Intent intent;

                    switch (menuBean.getCode()) {
                        case HomeMenuUtil.CODE_IT:
                            startActivity(new Intent(HomeActivity.this, ITActivity.class)
                                    .putExtra("menuBean", menuBean));
                            break;
                        case HomeMenuUtil.CODE_RECEIVE:
                            intent = new Intent(HomeActivity.this, ReceiveActivity.class);
                            intent.putExtra("menu", menuBean.getTitle());
                            startActivity(intent);
                            break;
                        case HomeMenuUtil.CODE_ELIE:
                            intent = new Intent(HomeActivity.this, ElieActivity.class);
                            intent.putExtra("menu", menuBean.getTitle());
                            startActivity(intent);
                            break;
                        case HomeMenuUtil.CODE_ORDERS:
                            intent = new Intent(HomeActivity.this, OrderActivity.class);
                            intent.putExtra("menu", menuBean.getTitle());
                            startActivity(intent);
                            break;
                        case HomeMenuUtil.CODE_INFO:
                            intent = new Intent(HomeActivity.this, ProductInfoActivity.class);
                            intent.putExtra("menu", menuBean.getTitle());
                            startActivity(intent);
                            break;
                        case HomeMenuUtil.CODE_MERCHAND:
                            intent = new Intent(HomeActivity.this, MerchandiseActivity.class);
                            intent.putExtra("menu", menuBean.getTitle());
                            startActivity(intent);
                            break;

                        case HomeMenuUtil.CODE_FOOD_BANK:
                            intent = new Intent(HomeActivity.this, MerchandiseActivity.class);
                            intent.putExtra("menu", menuBean.getTitle());
                            startActivity(intent);
                            break;
                        case HomeMenuUtil.CODE_EXIT:
                            confirmationDialog.show(R.string.message_do_you_really_want_to_exit);
                            break;
                        default:
                            Toast.makeText(HomeActivity.this, "Menu Clicked", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void onSwipeRefreshingChange(boolean isSwipeRefreshing) {
                    swipeView.setRefreshing(isSwipeRefreshing);

                }

                @Override
                public void onSnackBarShow(String message) {
                    Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG)
                            .setAction(R.string.btn_dismiss, snackBarDismissOnClickListener).show();

                }

            });
            rvHome.setAdapter(adapter);
        } else {
            adapter.setLoadMore(false);
            adapter.setMenuListBean(viewModel.getMenuListBean());
            adapter.notifyDataSetChanged();
        }

        setProgressScreenVisibility(false, false);
    }


    public void goToSubMenu(View view) {
        startActivity(new Intent(getApplicationContext(), ITActivity.class));
    }

    public void goToFileTransfer(View view) {
        startActivity(new Intent(getApplicationContext(), FileTransferActivity.class));
    }

    public void goToWaste(View view) {
        startActivity(new Intent(getApplicationContext(), WasteActivity.class));
    }

    public void goToPitNumber(View view) {
        startActivity(new Intent(getApplicationContext(), PitNumberActivity.class));
    }

   /* private String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }*/

   /* protected void processScannedData(String scanData) {
        XmlPullParserFactory pullParserFactory;
        String tempVal = null;
        try {
            // init the parserfactory
            pullParserFactory = XmlPullParserFactory.newInstance();
            // get the parser
            XmlPullParser parser = pullParserFactory.newPullParser();

            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(new StringReader(scanData));

            // parse the XML
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_DOCUMENT) {
                    Log.d("Rajdeol", "Start document");
                } else if (eventType == XmlPullParser.START_TAG) {
                    tempVal = parser.getAttributeValue(null, "Menu");
                    if (tempVal != null)
                        mainMenuList.add(tempVal);

                } else if (eventType == XmlPullParser.END_TAG) {
                    Log.d("Rajdeol", "End tag " + parser.getName());

                } else if (eventType == XmlPullParser.TEXT) {
                    Log.d("Rajdeol", "Text " + parser.getText());

                }
                eventType = parser.next();
            }

            // display the data on screen
            displayScannedData();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }// EO function

    private void displayScannedData() {
        String str = "";
        for (String model :
                mainMenuList) {
            str += model;
        }
        //Toast.makeText(this, ""+ str, Toast.LENGTH_SHORT).show();
    }*/
}
