package com.clonejw.telecine.activities;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.clonejw.telecine.R;

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

import java.util.ArrayList;

import static android.widget.Toast.LENGTH_LONG;

public class RegisterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener  {
    Context context;
    ArrayList<String> idclass = new ArrayList<>();
    int idplan ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        final ArrayList<String> classes = new ArrayList<>();


        final Spinner spinner = findViewById(R.id.planinfo);
        final ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(this,R.layout.spinner_item, classes);
        spinner.setOnItemSelectedListener(this);
        Button btn_login = (Button) findViewById(R.id.btn_login);
        Button backMenu = (Button) findViewById(R.id.backMenu);

        Button register          = (Button) findViewById(R.id.registerbtn);


        backMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(), LogActivity.class );
                startActivity(i);
                finish();
            }
        });
//PLANOO
        Resources resources11;
        resources11 = getResources();

        String url11 = resources11.getString(R.string.linksite)+"/api.php?action=plan";
        JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, url11,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        try {


                            for(int i = 0; i <= response.length(); i++) {
                                JSONObject result = response.getJSONObject(i);
                                String titulo = result.get("titulo").toString();
                                String value  = result.get("val").toString();
                                String tempo  = result.get("tempo").toString();
                                String id  = result.get("id").toString();
                                classes.add(id+"-- "+ titulo+" - Tempo: "+tempo+" Mês(es)"+value+"R$");
                            }




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

                        spinner.setAdapter(adapterSpinner);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), LENGTH_LONG).show();
                    }
                });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

//Cadastro Campos
        RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(2400);
        rotate.setInterpolator(new LinearInterpolator());
        rotate.setRepeatCount(Animation.INFINITE);

        ImageView loading = (ImageView) findViewById(R.id.loadingimg);
        loading.startAnimation(rotate);

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText input          = (EditText) findViewById(R.id.inputail);
                EditText user      = (EditText) findViewById(R.id.userinput);
                EditText passwo     = (EditText) findViewById(R.id.passwordinput);

                String email        = input.getText().toString();
                String username        = user.getText().toString();
                String password        = passwo.getText().toString();

                if(email.contains("@")){
                    if(username.trim().equals("") == false) {
                        if(password.trim().equals("") == false) {

                            final LinearLayout loadingscreen = findViewById(R.id.loadingscreen);

                            loadingscreen.setVisibility(View.VISIBLE);

                            Resources resources;
                            resources = getResources();
                            String url = resources.getString(R.string.linksite)+"/api.php?action=cadastro&login=" + username + "&mail=" + email + "&pass=" + password + "&idplan="+idplan+"&token=1234567654343245516712738123";

                            ////////
                            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                                    new Response.Listener<String>() {
                                        @Override
                                        public void onResponse(String response) {



                                            JSONObject obj = null;
                                            try {
                                                obj = new JSONObject(response);
                                                loadingscreen.setVisibility(View.INVISIBLE);
                                                    String linkpg = obj.get("linkpg").toString();

                                                    Intent i = new Intent(Intent.ACTION_VIEW);
                                                    i.setData(Uri.parse(linkpg));
                                                    startActivity(i);


                                                Toast.makeText(getApplicationContext(), obj.get("msg").toString(), Toast.LENGTH_LONG).show();
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }


                                        }
                                    },
                                    new Response.ErrorListener() {
                                        @Override
                                        public void onErrorResponse(VolleyError error) {
                                            //displaying the error in toast if occurrs
                                            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });

                            //creating a request queue
                            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                            requestQueue.add(stringRequest);
                            //adding the string request to request queue


                            /////////
                        }else{
                            Toast.makeText(getApplicationContext(), "Senha Invalido", Toast.LENGTH_LONG).show();
                        }
                    }else{
                        Toast.makeText(getApplicationContext(), "Nome de usuario Invalido", Toast.LENGTH_LONG).show();
                    }
             }else{
                    Toast.makeText(getApplicationContext(), "Email Invalido", Toast.LENGTH_LONG).show();
                }
            }
        });



    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        String text = adapterView.getItemAtPosition(i).toString();

        String split[] = text.split("--");
        idplan = Integer.parseInt(split[0]);


    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}
