package com.tomas.st_nset;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.st_nset.lib.Scanner;
import com.tomas.st_nset.lib.Settings;
import com.tomas.st_nset.lib.User;
import com.tomas.st_nset.lib.common.AsyncHttpClient;
import com.tomas.st_nset.lib.common.Utils;

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

import java.util.LinkedHashMap;
import java.util.Map;

public class LoginActivity_old extends Scanner implements View.OnClickListener {
    EditText edt_code;
    Map<String, User> mapUser;
    User users;
    private static int title_click = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        mapUser = new LinkedHashMap<>();
        edt_code = (EditText)findViewById(R.id.edt_usercode);

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

        // initial
        init();
    }

    private void init() {
        mapUser.clear();

        // download user data from web
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            new AsyncHttpClient(getApplicationContext()
                    ,Settings.getMgmtList().get("web_api") + "/users.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;

                        for (int i=0;i<jArray.length();i++) {
                            Log.d(getString(R.string.tag), String.valueOf(i));
                            String id = jArray.getJSONObject(i).getString("id");
                            Log.d(getString(R.string.tag), id);
                            String name = jArray.getJSONObject(i).getString("name");
                            String dept = jArray.getJSONObject(i).getString("dept_id");
                            String role = jArray.getJSONObject(i).getString("auth_id");
                            String password = jArray.getJSONObject(i).getString("password");
                            String status = jArray.getJSONObject(i).getString("status");

                            Log.d(getString(R.string.tag), id + " " + name);

                            mapUser.put(id, new User(id, name, password, dept, role, status));
                        }

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

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        try {

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

            edt_code.setText(data.trim());

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

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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                String str_code = edt_code.getText().toString().trim();

                if (mapUser.containsKey(str_code)){
                        User user_item = mapUser.get(str_code);
                        users = new User(
                                user_item.getId(),
                                user_item.getName(),
                                user_item.getPassword(),
                                user_item.getDepartment(),
                                user_item.getRole(),
                                user_item.getStatus());
                    Log.d(getString(R.string.tag), user_item.getId()+"|"+ user_item.getName());
                        Settings.setLoginUser(users);
                    // Discard the ScanManager class instance.
                    mScanManager.removeDataListener(LoginActivity_old.this);
                    // Discard the ScanManager class instance to release the resources.
                    mScanManager.releaseScanManager();
                    Intent intent1 = new Intent(LoginActivity_old.this, MainActivity.class);
                    startActivity(intent1);

                }else {
                    Toast.makeText(getApplicationContext(), "User not found!", Toast.LENGTH_LONG).show();
                    return;
                }
            break;

            case R.id.layout_menu_title:
                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(LoginActivity_old.this, SettingActivity.class);
                    startActivity(intent);
                    finish();
                }
        }


    }

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

    @Override
    public void onBackPressed() {
        finishAffinity();
        System.exit(0);
    }
}