package com.tomastc.bta500;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.bta500.lib.KeyMapping;
import com.tomastc.bta500.lib.Scanner;
import com.tomastc.bta500.lib.Settings;
import com.tomastc.bta500.lib.ShiftCode;
import com.tomastc.bta500.lib.SpinAdapter;
import com.tomastc.bta500.lib.UserInfo;
import com.tomastc.bta500.lib.WorkShopNo;
import com.tomastc.bta500.lib.common.AsyncHttpClient;
import com.tomastc.bta500.lib.common.Utils;
import com.tomastc.bta500.lib.UserLogin_list;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends Scanner {

    private Button btn_login, btn_completion, btn_ng_label, btn_close, btn_compo_detail, btn_direct_labor;
    private ImageButton btn_add_user;
    private TextView lbl_main_title, lbl_err, lbl_shift_code, lbl_work_shop_no, lbl_version;
    private RelativeLayout layout_login, layout_menu;
    private EditText txt_user_code;
    private Spinner ddl_shift_code, ddl_work_shop_no;

    private SpinAdapter shiftCodeArrayAdapter, workshopNoArrayAdapter;

    private UserInfo userInfo = null;
    private ShiftCode shiftCode;
    private WorkShopNo workShopNo;

    private static int title_click = 0;
    private int scan_step = 0;
    private List< UserLogin_list> user_lists;
    private Map<String, UserLogin_list>user_map;
    boolean check_userid;
    private String str_user_id, str_user_name;
    ListView listView_user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        check_userid = false;

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        user_lists = new ArrayList<UserLogin_list>();
        user_map = new LinkedHashMap<>();

        // read settings from Internal storage
        Settings.init(MainActivity.this);

        // Layout
        layout_login = (RelativeLayout) findViewById(R.id.layout_login);
        layout_menu = (RelativeLayout) findViewById(R.id.layout_menu);

        // Visibility
        layout_login.setVisibility(RelativeLayout.VISIBLE);
        layout_menu.setVisibility(RelativeLayout.GONE);

        // Button
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_completion = (Button) findViewById(R.id.btn_completion);
        btn_ng_label = (Button) findViewById(R.id.btn_ng_label);
        btn_close = (Button) findViewById(R.id.btn_close);
        btn_add_user = (ImageButton)findViewById(R.id.btn_add) ;
        btn_compo_detail = (Button) findViewById(R.id.btn_compo_detail);
        btn_direct_labor  = (Button) findViewById(R.id.btn_direct_labor);

        // EditText
        txt_user_code = (EditText) findViewById(R.id.txt_user_code);

        // Spinner
        ddl_shift_code = findViewById(R.id.ddl_shift_code);
        ddl_work_shop_no = findViewById(R.id.ddl_work_shop_no);

        // Textview
        lbl_main_title = (TextView) findViewById(R.id.lbl_main_title);
        lbl_err = (TextView) findViewById(R.id.lbl_err);
        lbl_shift_code = (TextView) findViewById(R.id.lbl_shift_code);
//        lbl_work_shop_no = (TextView) findViewById(R.id.lbl_work_shop_no);
        lbl_version = (TextView) findViewById(R.id.lbl_version);
        lbl_version.setText("v." + BuildConfig.VERSION_NAME);

        listView_user = (ListView) findViewById(R.id.view_user);


        // Hidden screen
        lbl_main_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (++title_click == 7) {
                    title_click = 0;

                    Toast.makeText(getApplicationContext(), "Settings mode!", Toast.LENGTH_LONG).show();

                    // call Settings activity
                    Log.d(getString(R.string.tag), "start settings activity");
                    Intent intent =new Intent(MainActivity.this, SettingsActivity.class);
                    startActivity(intent);
                }
            }
        });

        // Button click event
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (user_map.size() == 0){
                if (user_lists.size() == 0){
                    lbl_err.setText("please add user code");
                    lbl_err.setVisibility(View.VISIBLE);
                }else{
                    doLoginSuccess();
                }
//                if (txt_user_code.getText().toString().trim().isEmpty()) {
//                    lbl_err.setText("Invalid user code");
//                    lbl_err.setVisibility(View.VISIBLE);
//                } else if (userInfo == null) {
//                    // Validate the user code for Manual mode
//                    String error_msg = "User code not found!";
//                    try {
//                        JSONObject json = new JSONObject();
//                        json.put("cmd", "search");
//                        json.put("id", txt_user_code.getText().toString());
//
//                        Toast.makeText(getApplicationContext(), "Check manual user code, please wait.", Toast.LENGTH_LONG).show();
//                        new AsyncHttpClient(getApplicationContext()
//                                ,Settings.getMgmtList().get("web_api") + "/nst_user_master.php"
//                                , json.toString()
//                        ) {
//                            @Override
//                            public void onFinished(String response, int resp_code) {
//                                Log.d(getString(R.string.tag), "response: " + response);
//                                // update mapItems
//                                try {
//                                    JSONArray jArray = new JSONArray(response);
//                                    Log.d(getString(R.string.tag), "response json length: " + jArray.length());
//                                    JSONObject jsonObject = jArray.getJSONObject(0);
//                                    if (jArray.length() != 0) { // found user
//                                        userInfo = new UserInfo(
//                                                jsonObject.getString("id")
//                                                , jsonObject.getString("name")
//                                                , ""
//                                        );
//
//                                        doLoginSuccess();
//                                    } else {
//                                        throw new JSONException("User not found!");
//                                    }
//
//                                } catch (JSONException e) {
//                                    Log.e(getString(R.string.tag), e.getMessage());
//                                    lbl_err.setText(error_msg);
//                                    lbl_err.setVisibility(View.VISIBLE);
//                                }
//                            }
//                        }
//                                .execute();
//                    } catch (JSONException e) {
//                        Log.e(getString(R.string.tag), e.getMessage());
//                        lbl_err.setText(error_msg);
//                        lbl_err.setVisibility(View.VISIBLE);
//                    }
//
//                } else {
//
//                    doLoginSuccess();
//                }
            }
        });
        btn_completion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(getString(R.string.tag), "start completion activity");
                Settings.setWorkMode(Settings.WorkMode.COMPLETION);
                Intent intent =new Intent(MainActivity.this, CompletionActivity.class);
                startActivity(intent);
            }
        });
        btn_ng_label.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(getString(R.string.tag), "start NG label activity");
                Settings.setWorkMode(Settings.WorkMode.NG_LABEL);
                Intent intent =new Intent(MainActivity.this, CompletionActivity.class);
                startActivity(intent);
            }
        });
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finishAffinity();
                System.exit(0);
            }
        });

        txt_user_code.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                check_userid = false;
                scan_step = 0;
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                    if (motionEvent.getX()>(view.getWidth()-24)){
                        ((EditText)view).setText("");
                    }
                }
                return false;
            }
        });

        btn_add_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(getString(R.string.tag), "check_userid: " + check_userid);

                if (check_userid == false){
                    //key manual check userid --> add to map
                    String error_msg = "User code not found!";
                    try {
                        JSONObject json = new JSONObject();
                        json.put("cmd", "search");
                        json.put("id", txt_user_code.getText().toString());

                        Toast.makeText(getApplicationContext(), "Check manual user code, please wait.", Toast.LENGTH_LONG).show();
                        new AsyncHttpClient(getApplicationContext()
                                ,Settings.getMgmtList().get("web_api") + "/nst_user_master.php"
                                , json.toString()
                        ) {
                            @Override
                            public void onFinished(String response, int resp_code) {
                                Log.d(getString(R.string.tag), "response: " + response);
                                // update mapItems
                                try {
                                    JSONArray jArray = new JSONArray(response);
                                    Log.d(getString(R.string.tag), "response json length: " + jArray.length());
                                    JSONObject jsonObject = jArray.getJSONObject(0);
                                    if (jArray.length() != 0) { // found user

                                        str_user_id = jsonObject.getString("id");
                                        str_user_name = jsonObject.getString("name");

//                                        userInfo = new UserInfo(
//                                                jsonObject.getString("id")
//                                                , jsonObject.getString("name")
//                                                , ""
//                                        );

//                                        doLoginSuccess();
                                        //add to map
                                        Add_Map_Users();
                                    } else {
                                        throw new JSONException("User not found!");
                                    }

                                } catch (JSONException e) {
                                    Log.e(getString(R.string.tag), e.getMessage());
                                    lbl_err.setText(error_msg);
                                    lbl_err.setVisibility(View.VISIBLE);
                                }
                            }

                            @Override
                            protected void onError(Exception e) {

                            }
                        }.execute();
                    } catch (JSONException e) {
                        Log.e(getString(R.string.tag), e.getMessage());
                        lbl_err.setText(error_msg);
                        lbl_err.setVisibility(View.VISIBLE);
                    }


                }else {//scan user id

                    Add_Map_Users();
                }
            }
        });

        /**
         * Version 1.4.0
         */
        btn_compo_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(getString(R.string.tag), "start component detail activity");
                Settings.setWorkMode(Settings.WorkMode.COMPONENT_DETAIL);
                Intent intent =new Intent(MainActivity.this, ComponentDetailActivity.class);
                startActivity(intent);

            }
        });

        btn_direct_labor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(getString(R.string.tag), "start direct labor activity");
                Settings.setWorkMode(Settings.WorkMode.DIRECT_LABOR);
                Intent intent = new Intent(MainActivity.this, DirectLaborActivity.class);
                startActivity(intent);
            }
        });


        // initial
        init();
    }

    private void Add_Map_Users() {
        Settings.setShiftCode((ShiftCode) shiftCodeArrayAdapter.getItem(ddl_shift_code.getSelectedItemPosition()));
        Settings.setWorkShopNo((WorkShopNo) workshopNoArrayAdapter.getItem(ddl_work_shop_no.getSelectedItemPosition()));
        Log.d(getString(R.string.tag),  Settings.getShiftCode().getId()
                +"|"+Settings.getWorkShopNo().getId()
                +"|"+Settings.getWorkShopNo().getWs_no()
                +"|"+Settings.getWorkShopNo().getWs_desc());

        if (user_lists.stream().anyMatch(o -> o.getWs_no().equals(Settings.getWorkShopNo().getWs_no()))){
            lbl_err.setText("This WorkShop already exists");
            lbl_err.setVisibility(View.VISIBLE);

        }else{
            ddl_shift_code.setEnabled(false);

            user_lists.add(
                    new UserLogin_list(
                            str_user_id,
                            str_user_name,
                            Settings.getShiftCode().getId(),
                            Settings.getWorkShopNo().getWs_cd(),
                            Settings.getWorkShopNo().getWs_no(),
                            Settings.getWorkShopNo().getMc_line_no(),
                            Settings.getWorkShopNo().getWs_desc(),
                            Settings.getWorkShopNo().getUpd_date(),
                            Settings.getWorkShopNo().getUpd_user_id(),
                            Settings.getWorkShopNo().getPrint_preset()));

            Log.d(getString(R.string.tag),String.valueOf(user_lists.size()));

            ArrayList<HashMap<String, String>> MyArraylist = new ArrayList<HashMap<String, String>>();
            String user, shift, ws_no;

        for (int i = 0; i<user_lists.size(); i++){
                user = user_lists.get(i).getUser_id();
                shift = user_lists.get(i).getShift();
                ws_no = user_lists.get(i).getWs_no();
                Log.d(getString(R.string.tag),user+"|"+shift+"|"+ws_no);

                HashMap<String, String> data;
                data = new HashMap<String, String>();
                data.put("A",user+", "+shift+", "+ws_no);
                MyArraylist.add(data);

            }

            SimpleAdapter ADA;
            ADA = new SimpleAdapter(MainActivity.this, MyArraylist, R.layout.content_user_login,
                    new String[]{"A"}, new int[]{R.id.txt_list_login});
            listView_user.setAdapter(ADA);
            Log.d(getString(R.string.tag), "set adapter");

        }
    }


    private void init() {
        // set shift
        try {
            Log.d(getString(R.string.tag), "Extract shift_code:" + Settings.getMgmtList().get("shift_code"));
            String[] tmp_ = Settings.getMgmtList().get("shift_code").split("\\|");
            Log.d(getString(R.string.tag), Arrays.deepToString(tmp_));
            ShiftCode[] shiftCode_ = new ShiftCode[tmp_.length];
            for(int i=0; i<tmp_.length; i++) {
                shiftCode_[i] = new ShiftCode(tmp_[i], tmp_[i]);
            }

            Log.d(getString(R.string.tag), Arrays.deepToString(shiftCode_));

            // Setup drop down list
            shiftCodeArrayAdapter = new SpinAdapter(
                    getApplicationContext(), R.layout.spinner_usr_list, shiftCode_);
            ddl_shift_code.setAdapter(shiftCodeArrayAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }


        // download work shop no data from web
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            new AsyncHttpClient(getApplicationContext()
                    ,Settings.getMgmtList().get("web_api") + "/nst_ws_machine_master.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());
                        if (jArray.length() == 0)
                            return;

                        WorkShopNo[] workShopNo_ = new WorkShopNo[jArray.length()];
                        for (int i=0;i<jArray.length();i++) {
                            String ws_cd = jArray.getJSONObject(i).getString("ws_cd");
                            String ws_no = jArray.getJSONObject(i).getString("ws_no");
                            String mc_line_no = jArray.getJSONObject(i).getString("mc_lineno");
                            String ws_desc = jArray.getJSONObject(i).getString("ws_desc");
                            String upd_date = jArray.getJSONObject(i).getString("upd_date");
                            String upd_user_id = jArray.getJSONObject(i).getString("upd_user_id");
                            String print_preset = jArray.getJSONObject(i).getString("print_preset");
                            String interlock = jArray.getJSONObject(i).getString("INTERLOCK");
                            workShopNo_[i] = new WorkShopNo(ws_cd, ws_no, mc_line_no, ws_desc, upd_date, upd_user_id, print_preset, interlock);
                        }

                        Log.d(getString(R.string.tag), Arrays.deepToString(workShopNo_));

                        // Setup drop down list
                        workshopNoArrayAdapter = new SpinAdapter(
                                getApplicationContext(), R.layout.spinner_usr_list, workShopNo_);
                        ddl_work_shop_no.setAdapter(workshopNoArrayAdapter);

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

                @Override
                protected void onError(Exception e) {

                }
            }
                    .execute();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
//        check_userid = false;
        try {

            lbl_err.setVisibility(View.INVISIBLE);
            Log.d(getString(R.string.tag), "data read:" + data);

            // check if code is empty => step 1
            if (txt_user_code.getText().toString().trim().isEmpty()) {
                txt_user_code.setText(data.trim());

                // Validate user code
                try {
                    JSONObject json = new JSONObject();
                    json.put("cmd", "search");
                    json.put("id", data.trim());

                    new AsyncHttpClient(getApplicationContext()
                            ,Settings.getMgmtList().get("web_api") + "/nst_user_master.php"
                            , json.toString()
                    ) {
                        @Override
                        public void onFinished(String response, int resp_code) {
                            Log.d(getString(R.string.tag), "response: " + response);
                            // update mapItems
                            try {
                                JSONArray jArray = new JSONArray(response);
                                Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                                if (jArray.length() > 0) {
                                    JSONObject jsonObject = jArray.getJSONObject(0);
                                    str_user_id = jsonObject.getString("id");
                                    str_user_name =  jsonObject.getString("name");

                                    scan_step = 1;
                                    check_userid = true;
                                    Log.d(getString(R.string.tag), "check_userid: " + check_userid);
//                                    userInfo = new UserInfo(
//                                            jsonObject.getString("id")
//                                            , jsonObject.getString("name")
//                                            , ""
//                                    );

                                } else {
                                    lbl_err.setText("User not found!");
                                    lbl_err.setVisibility(View.VISIBLE);
                                }

                            } catch (JSONException e) {
                                Log.e(getString(R.string.tag), e.getMessage());
                                lbl_err.setText("Incorrect scan information");
                                lbl_err.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        protected void onError(Exception e) {

                        }
                    }
                            .execute();
                } catch (JSONException e) {
                    Log.e(getString(R.string.tag), e.getMessage());
                    lbl_err.setText("Incorrect scan information");
                    lbl_err.setVisibility(View.VISIBLE);
                }

            } else {
                scan_step = 2;
                WorkShopNo workShopNo = (WorkShopNo)workshopNoArrayAdapter.findItem(data);
                if (workShopNo != null) {
                    int pos = workshopNoArrayAdapter.getPosition(workShopNo);
                    Log.d(getString(R.string.tag), "workShopNo list index:" + pos);
                    ddl_work_shop_no.setSelection(pos);
                } else {
                    lbl_err.setText("Work shop not found.");
                    lbl_err.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(), "Work shop no[" + data + "] not found!",
                            Toast.LENGTH_LONG).show();
                }
            }

            // always hide keyboard after scan
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void doLoginSuccess() {

        // Set login information
//        Settings.setUserInfoX(userInfo);
//        Settings.setShiftCode((ShiftCode) shiftCodeArrayAdapter.getItem(ddl_shift_code.getSelectedItemPosition()));
//        Settings.setWorkShopNo((WorkShopNo) workshopNoArrayAdapter.getItem(ddl_work_shop_no.getSelectedItemPosition()));

        // Set header information
        lbl_shift_code.setText("Shift code : " + Settings.getShiftCode().getId());
//        lbl_work_shop_no.setText("Work shop no : " + Settings.getWorkShopNo().getId());

        Settings.setUserLogin_list((user_lists));
        Log.d(getString(R.string.tag), "login_size: " + Settings.getUserLogin_list().size());

        // Discard the ScanManager class instance.
        mScanManager.removeDataListener(MainActivity.this);
        // Discard the ScanManager class instance to release the resources.
        mScanManager.releaseScanManager();

        layout_login.setVisibility(RelativeLayout.GONE);
        layout_menu.setVisibility(RelativeLayout.VISIBLE);
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
            && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finishAffinity();
                    System.exit(0);
                    break;

                case P2:
                    btn_completion.performClick();
                    break;

                case P3:
                    btn_ng_label.performClick();
                    break;

                case P4:
                    btn_compo_detail.performClick();
                    break;

            }
        } else if (keyCode == KeyMapping.ENT.getId()) {
            btn_login.performClick();
            return false;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

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

}