package com.tomas.ht_ydt;

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


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

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

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Login_Activity extends Scanner implements View.OnClickListener  {
    EditText edt_password, edt_userid;
    Button btn_login;

    String Username, Password;
    User users;
    private TextView lbl_main_title;
    //    private SpinAdapter usrListArrayAdapter;
    private static int title_click = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        edt_userid = (EditText) findViewById(R.id.edt_userid);
        edt_password = (EditText) findViewById(R.id.edt_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        lbl_main_title = (TextView) findViewById(R.id.lbl_main_title);

        // 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_userid.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 view) {
        switch (view.getId()) {
            case R.id.btn_login:

                btn_login.setEnabled(false);
                btn_login.setBackgroundResource(R.drawable.button_background_gray);
                Username = edt_userid.getText().toString().trim();
                Password = edt_password.getText().toString().trim();

                if (Username.trim().equals("")||Password.trim().equals("")){
                    btn_login.setEnabled(true);
                    btn_login.setBackgroundResource(R.drawable.button_background_blue);
                    showWarning("Please complete the information");

                }else {
                    Check_user();

                }
                break;


            case R.id.lbl_main_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, Setting_Activity.class);
                    startActivity(intent);

                }
        }

    }

    private void Check_user() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("user_id", Username);
            json.put("password", Password);


            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){
                            showWarning("Invalid username or password");
                            btn_login.setEnabled(true);
                            btn_login.setBackgroundResource(R.drawable.button_background_blue);

                        }else {
                            for (int i=0;i<jArray.length();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");
                                users = new User(id, name, password,dept,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();
                            Intent intent1 = new Intent(Login_Activity.this, MainActivity.class);
                            startActivity(intent1);
                        }


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

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

    }

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

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