package w.soulofpluto.posstock;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.JSON;

 /*
  Create by Ramesh Babu
 */

public class Login extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener{
    private EditText userId, password;
    private Spinner storeId;
    private Button submit;
    private ArrayList<Store> stores;
    private String Response;
    private int Store_Id;
    private Toolbar login_toolbar;
    private PreferenceManager preferenceManager;
    private String Store_Name;

    public static void logout(Context context){
        Activity activity = (Activity) context;
        Intent in_logout = new Intent(context, Login.class);
        in_logout.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(in_logout);
        activity.finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        userId = findViewById(R.id.userId);
        password = findViewById(R.id.password);
        storeId = findViewById(R.id.storeId);
        submit = findViewById(R.id.submit);
        login_toolbar = findViewById(R.id.login_toolbar);
        setSupportActionBar(login_toolbar);
        getSupportActionBar().setTitle(getResources().getString(R.string.login));
        preferenceManager = new PreferenceManager(this);
        submit.setOnClickListener(this);
        storeId.setOnItemSelectedListener(this);
        password.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            public void onFocusChange(View view, boolean hasFocus){
                if(!hasFocus){
                }else{
                   if(Constants.isNetworkAvailable(Login.this)){
                        if(userId.getText().toString().length() > 3){
                          StoreId(userId.getText().toString());
                          Constants.ProgressDialogShow(Login.this);
                        }
                   }else{
                      Constants.getToast(Login.this, getResources().getString(R.string.connection));
                   }
                }
            }
        });
    }

    private void StoreId(String Id){
        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constants.StoreId + Id)
                .get()
                .addHeader(Constants.Type, Constants.App_json)
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, final IOException e){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Login.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        Constants.ProgressDialogDismiss();
                    }
                });
            }
            @Override
            public void onResponse(final com.squareup.okhttp.Response response) throws IOException{
                try{
                    Constants.ProgressDialogDismiss();
                    final String Response = response.body().string();
                    Log.e("Store Response ", Response);
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){
                        @Override
                        public void run(){
                            try{
                                if(response.code() == 200){
                                  JSONObject object = new JSONObject(Response);
                                    stores = new ArrayList<>();
                                    if(object.has(getResources().getString(R.string.success))){
                                        if(object.getInt(getResources().getString(R.string.success)) == 1){
                                            if(object.has(getResources().getString(R.string.data))){
                                                JSONArray jsonArray = object.getJSONArray(getResources().getString(R.string.data));
                                                if(jsonArray.length() > 0){
                                                    for(int i = 0; i < jsonArray.length(); i++){
                                                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                                                        Store store = new Store();
                                                        store.setStoreId(jsonObject.getInt(getResources().getString(R.string.id)));
                                                        store.setStoreName(jsonObject.getString(getResources().getString(R.string.store_name)));
                                                        stores.add(store);
                                                    }
                                                    ArrayAdapter<Store> adapter = new ArrayAdapter<Store>(Login.this, android.R.layout.simple_dropdown_item_1line, stores);
                                                    storeId.setAdapter(adapter);
                                                }
                                            }
                                        }else{
                                            Toast.makeText(Login.this, getResources().getString(R.string.no_stores), Toast.LENGTH_SHORT).show();
                                            storeId.setAdapter(null);
                                        }
                                    }
                                }else{
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                       Constants.getToast(Login.this,Response);
                                        }
                                    });
                                }
                            }catch(JSONException e){
                               e.printStackTrace();
                            }
                        }
                    });
                }catch (NullPointerException io) {
                    io.printStackTrace();
                } finally {
                    response.body().close();
                }
            }
        });
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.submit:
                if(TextUtils.isEmpty(userId.getText().toString()) && TextUtils.isEmpty(password.getText().toString())){
                    Toast.makeText(Login.this, getResources().getString(R.string.val_empandpass), Toast.LENGTH_SHORT).show();
                }else if(TextUtils.isEmpty(userId.getText().toString())){
                    Toast.makeText(Login.this, getResources().getString(R.string.val_empid), Toast.LENGTH_SHORT).show();
                }else if(TextUtils.isEmpty(password.getText().toString())){
                    Toast.makeText(Login.this, getResources().getString(R.string.val_pass), Toast.LENGTH_SHORT).show();
                }else{
                    if(Constants.isNetworkAvailable(Login.this)){
                        doLogin(userId.getText().toString(), password.getText().toString());
                        Constants.ProgressDialogShow(Login.this);
                        /*JSONObject object = new JSONObject();
                        try{
                            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                                object.put(getResources().getString(R.string.empid), userId.getText().toString());
                                object.put(getResources().getString(R.string.password), Constants.getSHA256(password.getText().toString()));
                                object.put(getResources().getString(R.string.storeid), Store_Id);
                                object.put(getResources().getString(R.string.dongle), false);
                                object.put(getResources().getString(R.string.android_version),Constants.VERSION);
                                Log.e("post object ",object.toString());
                            }
                        }catch(JSONException e){
                            e.printStackTrace();
                        }
                        ApiService service = Getretrofit.getClient().create(ApiService.class);
                        //service.login(object);
                        RequestBody body = RequestBody.create(JSON, object.toString());
                        Call<Response> call  = service.login(body);
                        call.enqueue(new retrofit2.Callback<com.squareup.okhttp.Response>(){
                            @Override
                            public void onResponse(Call<com.squareup.okhttp.Response> call, retrofit2.Response<com.squareup.okhttp.Response> response){
                                Log.e("Login",response.toString());
                                Log.e("Login",String.valueOf(response.isSuccessful()));
                            }
                            @Override
                            public void onFailure(Call<com.squareup.okhttp.Response> call, Throwable t){
                                Log.e("Fail",String.valueOf(t.getCause()));
                                Log.e("Fail",String.valueOf(t.getMessage()));
                                Log.e("Fail",String.valueOf(t.getLocalizedMessage()));
                            }
                        });*/
                    }else{
                       Constants.getToast(Login.this, getResources().getString(R.string.connection));
                    }
                }
                break;
        }
    }

    private void doLogin(String userId, final String pass){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                object.put(getResources().getString(R.string.empid), userId);
                object.put(getResources().getString(R.string.password), Constants.getSHA256(pass));
                object.put(getResources().getString(R.string.storeid), Store_Id);
                object.put(getResources().getString(R.string.dongle), false);
                object.put(getResources().getString(R.string.android_version),Constants.VERSION);
                Log.e("post object ",object.toString());
            }
        }catch(JSONException e){
          e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON, object.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(240, TimeUnit.SECONDS);
        client.setReadTimeout(240, TimeUnit.SECONDS);
        client.setWriteTimeout(240, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Constants.Login)
                .post(body)
                .addHeader(Constants.Type, Constants.App_json)
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, IOException e){
                if(e.getCause() != null && e.getCause() instanceof UnknownHostException){
                }else{
                  Log.e("error ====>", e.getMessage());
                }
                Constants.ProgressDialogDismiss();
            }
            @Override
            public void onResponse(final Response response) throws IOException{
                Constants.ProgressDialogDismiss();
                Response = response.body().string();
                Log.e("Login",Response);
                try{
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){
                        @Override
                        public void run(){
                            if(response.code() == 200){
                                try{
                                    JSONObject obj = new JSONObject(Response);
                                    if(obj.has(getResources().getString(R.string.success))){
                                        if(obj.getInt(getResources().getString(R.string.success)) == 1){
                                            JSONObject data = obj.getJSONObject(getResources().getString(R.string.data));
                                            preferenceManager.setUserId(data.getString(getResources().getString(R.string.empid)));
                                            preferenceManager.setCustToken(data.getString(getResources().getString(R.string.usertoken)));
                                            preferenceManager.setStoreId(data.getString(getResources().getString(R.string.storeid)));
                                            preferenceManager.setPrefix(data.getString(getResources().getString(R.string.prefix)));
                                            preferenceManager.setPassword(Constants.getSHA256(pass));
                                            if (Store_Name != null)
                                                preferenceManager.setStoreName(Store_Name);
                                            preferenceManager.setLogged(true);
                                            Intent in = new Intent(Login.this, HomeActivity.class);
                                            startActivity(in);
                                            finish();
                                        } else {
                                            Toast.makeText(Login.this, obj.getString(getResources().getString(R.string.msg)), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }catch(JSONException e){
                                   e.printStackTrace();
                                }
                            } else {
                            }
                        }
                    });
                }catch(NullPointerException io){
                   io.printStackTrace();
                }finally{
                   response.body().close();
                }
            }
        });
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
        switch (parent.getId()){
            case R.id.storeId:
                Store store = stores.get(position);
                Store_Id = store.StoreId;
                Store_Name = store.StoreName;
                break;
        }
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
