package w.soulofpluto.posstock;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import static w.soulofpluto.posstock.Constants.JSON;
import static w.soulofpluto.posstock.Constants.getDateWithOffset;

public class MainActivity extends AppCompatActivity {
    Toolbar main_toolbar;
    RecyclerView plans_list;
    PreferenceManager preferenceManager;
    ArrayList<Plans> plansArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        main_toolbar = findViewById(R.id.main_toolbar);
        plans_list   = findViewById(R.id.plans_List);
        plansArrayList = new ArrayList<>();
        preferenceManager = new PreferenceManager(this);
        setSupportActionBar(main_toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(getResources().getString(R.string.test)+ "  UserId : " +preferenceManager.getUserId());
    }

    @Override
    protected void onStart(){
        if(Constants.isNetworkAvailable(MainActivity.this)){
           FetchData(Constants.Dashboard);
           Constants.ProgressDialogShow(MainActivity.this);
        }else{
           Constants.getToast(MainActivity.this,getResources().getString(R.string.connection));
        }
        super.onStart();
    }

    public void Logout(String Url){
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(250, TimeUnit.SECONDS);
        client.setReadTimeout(250,TimeUnit.SECONDS);
        client.setWriteTimeout(250,TimeUnit.SECONDS);
        final Request request = new Request.Builder()
                .url(Url)
                .get()
                .addHeader(Constants.Type, Constants.App_json)
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, IOException e){
                Constants.ProgressDialogDismiss();
            }
            @Override
            public void onResponse(Response response) throws IOException{
                Constants.ProgressDialogDismiss();
                if(response.isSuccessful()){
                    String res = response.body().string();
                    try{
                        JSONObject jsonObject = new JSONObject(res);
                        if(jsonObject.has(getResources().getString(R.string.success))){
                          if(jsonObject.getInt(getResources().getString(R.string.success)) == 1){
                              preferenceManager.setUserId("");
                              preferenceManager.setLogged(false);
                              preferenceManager.setCustToken("");
                              preferenceManager.setStoreId("");
                              Login.logout(MainActivity.this);
                          }else{
                              Constants.getToast(MainActivity.this,jsonObject.getString(getResources().getString(R.string.msg)));
                          }
                        }
                    }catch(JSONException e) {
                      e.printStackTrace();
                    }catch(NullPointerException np){
                      np.printStackTrace();
                    }
               }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
       switch(item.getItemId()){
           case android.R.id.home:
             finish();
            break;
           case R.id.dashboard_logout:
              if(Constants.isNetworkAvailable(MainActivity.this)){
                 Logout(Constants.Logout+preferenceManager.getUserId());
                 Constants.ProgressDialogShow(MainActivity.this);
              }else{
                 Constants.getToast(MainActivity.this,getResources().getString(R.string.connection));
              }
            break;
       }
       return super.onOptionsItemSelected(item);
    }

    private void FetchData(String Url){
        JSONObject object = new JSONObject();
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
                Date todayDate = new Date();
                Date from = getDateWithOffset(-Constants.Value, new Date());
                String fromDate = currentDate.format(from);
                String thisDate = currentDate.format(todayDate);
                Log.e("Last date",fromDate);
                object.put(getResources().getString(R.string.auditstatus),"In Progress");
                object.put(getResources().getString(R.string.fromdate),fromDate);
                object.put(getResources().getString(R.string.todate),thisDate);
                object.put(getResources().getString(R.string.android_version),Constants.VERSION);
            }
        }catch(JSONException e){
          e.printStackTrace();
        }
       RequestBody body = RequestBody.create(JSON,object.toString());
        final OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(250, TimeUnit.SECONDS);
        client.setReadTimeout(250, TimeUnit.SECONDS);
        client.setWriteTimeout(250, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(Url)
                .post(body)
                .addHeader(Constants.Type, Constants.App_json)
                .addHeader(getResources().getString(R.string.accesstoken),preferenceManager.getCustToken())
                .addHeader(getResources().getString(R.string.storeidtoken),preferenceManager.getStoreId())
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, final IOException e){
                runOnUiThread(new Runnable(){
                    @Override
                    public void run(){
                     Constants.getToast(MainActivity.this,e.getMessage());
                     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){
                                    final JSONObject object = new JSONObject(Response);
                                    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))){
                                                plansArrayList.clear();
                                                JSONArray jsonArray = object.getJSONArray(getResources().getString(R.string.data));
                                                for(int i = 0; i < jsonArray.length(); i++) {
                                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                                    Plans plans = new Plans();
                                                    plans.setPlanId(String.valueOf(jsonObject.getInt("id")));
                                                    plans.setName(jsonObject.getString("stock_audit_name"));
                                                    plans.setDivision(Constants.convertString(jsonObject.getString("item_divisions")));
                                                    plans.setSection(Constants.convertString(jsonObject.getString("item_sections")));
                                                    plansArrayList.add(plans);
                                                }
                                                CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, plansArrayList);
                                                plans_list.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false));
                                                plans_list.setAdapter(customAdapter);
                                            }else if (object.has(getResources().getString(R.string.msg))){
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        try {
                                                            Constants.getToast(MainActivity.this, object.getString(getResources().getString(R.string.msg)));
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            }
                                        }else if(object.getInt(getResources().getString(R.string.success)) == 3){
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try{
                                                       Constants.getToast(MainActivity.this, object.getString(getResources().getString(R.string.msg)));
                                                    }catch(JSONException e) {
                                                      e.printStackTrace();
                                                    }
                                                }
                                            });
                                            preferenceManager.setUserId("");
                                            preferenceManager.setLogged(false);
                                            preferenceManager.setCustToken("");
                                            preferenceManager.setStoreId("");
                                            Login.logout(MainActivity.this);
                                        }
                                    }
                                }
                            }catch(JSONException e){
                               e.printStackTrace();
                            }
                        }
                    });
                }catch(NullPointerException io){
                    io.printStackTrace();
                }finally{
                    response.body().close();
                }
            }
        });
    }
}