package com.tomas.st_nset;

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

import com.keyence.autoid.sdk.scan.DecodeResult;
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.Scanner;
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;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Login_Activity extends Scanner implements View.OnClickListener {

    EditText edt_code;
    Map<String, User> mapUser;
    User users;
    Button btn_login;
    String str_code, id, str_name, password, str_dept, str_role, status;
    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);
        btn_login = (Button) findViewById(R.id.btn_login);

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

    }
    @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:

                btn_login.setEnabled(false);
                str_code = edt_code.getText().toString().trim();

                if (str_code.trim().equals("")){
                    btn_login.setEnabled(true);
                    new SweetAlertDialog(Login_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Please complete the information")
                            .show();
                }else{
                    Check_user();
                }
                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(Login_Activity.this, SettingActivity.class);
                    startActivity(intent);
                    finish();
                }
        }
    }

    private void Check_user() {
//        list_item.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "check_user");
            json.put("user_id", str_code);

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

                        if (jArray.length() == 0){
                            new SweetAlertDialog(Login_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("User not found")
                                    .show();
                            edt_code.setText("");
                            btn_login.setEnabled(true);

                        }else {
                            for (int i=0;i<jArray.length();i++) {
                                 id = jArray.getJSONObject(i).getString("id");
                                Log.d(getString(R.string.tag), id);
                                 str_name = jArray.getJSONObject(i).getString("name");
                                 str_dept = jArray.getJSONObject(i).getString("dept_id");
                                 str_role = jArray.getJSONObject(i).getString("auth_id");
                                 password = jArray.getJSONObject(i).getString("password");
                                 status = jArray.getJSONObject(i).getString("status");
                            }

                                users = new User(id, str_name, password, str_dept, str_role, status);
                                Settings.setLoginUser(users);
                                // Discard the ScanManager class instance.
                                mScanManager.removeDataListener(Login_Activity.this);
                                // Discard the ScanManager class instance to release the resources.
                                mScanManager.releaseScanManager();

                                btn_login.setEnabled(true);
                                edt_code.setText("");
                                Intent intent1 = new Intent(Login_Activity.this, MainActivity.class);
                                startActivity(intent1);

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

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

    }

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

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