package com.b2lmobitech.spottest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.utils.MySnackbar;
import com.b2lmobitech.spottest.utils.Preference;
import com.google.firebase.iid.FirebaseInstanceId;

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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends AppCompatActivity {

    EditText userEmail,userPassword,userPassword2;
    private String build_code,versionname,installedtime,versioncode,updatedtime;
    private TextView itemTitle;
    private CheckBox checkItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        getWidgets();
    }

    private void getWidgets(){
        userEmail=findViewById(R.id.userEmail);
        userPassword=findViewById(R.id.userPassword);
        userPassword2=findViewById(R.id.userPassword2);
        itemTitle = findViewById(R.id.itemTitle);
        checkItem =  findViewById(R.id.checkItem);
        itemTitle.setMovementMethod(LinkMovementMethod.getInstance());
        Spannable sp = (Spannable) itemTitle.getText();
        ClickableSpan termclick = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(getApplicationContext(), WebActivity.class);
                intent.putExtra("url", "http://Www.fieldcloud.in/spottest/term_condition/Terms.html");
                startActivity(intent);
            }
        };
        ClickableSpan privacyclick = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(getApplicationContext(), WebActivity.class);
                intent.putExtra("url", "http://Www.fieldcloud.in/spottest/term_condition/Privacy.html");
                startActivity(intent);
            }
        };
        //SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(getString(R.string.termsandconditions));
        sp.setSpan(privacyclick,
                7, 21, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp.setSpan(termclick,
                26, sp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
       // itemTitle.setMovementMethod(LinkMovementMethod.getInstance());

        findViewById(R.id.signupButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isValid()){
                    build_code = "";
                    versionname = "";
                    installedtime = "";
                    versioncode = "";
                    updatedtime = "";
                    signUp();
                }
            }
        });

    }

    private boolean isValid(){
        MySnackbar snackbar=MySnackbar.getInstance(this);

        if(userEmail.getText().toString().isEmpty()){
            snackbar.show("Enter Id");
            return false;
        }

        if(userPassword.getText().toString().isEmpty()){
            snackbar.show("Enter Password");
            return false;
        }else if(userPassword.getText().toString().length()<6){
            snackbar.show("Password Should Consists atleast 6 characters");
            return false;
        }else if(!userPassword.getText().toString().equals(userPassword2.getText().toString())){
            snackbar.show("Passwords does not match");
            return false;
        }else if(!(checkItem.isChecked()))
        {
            snackbar.show("Please accept Privacy Policy and Terms");
            return false;
        }

        closeKeyboard();
        return true;
    }

    private void closeKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void signUp() {

        Map<String, String> params = new HashMap<>();
        params.put("pass", userPassword.getEditableText().toString());
        params.put("email", userEmail.getEditableText().toString());
        params.put("deviceid", FirebaseInstanceId.getInstance().getId());
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            askPermission();
            return;
        }
        params.put("imei", ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());

        MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.USER_SIGNUP, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    signUp(new JSONObject(response));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void signUp(JSONObject jsonObject) throws JSONException {
        if(jsonObject.getInt("s")==1){
            Toast.makeText(getApplicationContext(),jsonObject.getString("m"),Toast.LENGTH_SHORT).show();
            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
            finish();
        }
        else if(jsonObject.getInt("s")==3){
            Toast.makeText(getApplicationContext(),jsonObject.getString("m"),Toast.LENGTH_SHORT).show();
//            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
//            finish();
            get_currentversion();
        }
        else{
            MySnackbar snackbar=MySnackbar.getInstance(this);
            snackbar.show(jsonObject.getString("m"));
        }
    }

    private void askPermission(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

// Add the buttons
        builder.setPositiveButton("GO TO SETTING", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)));
            }
        });

        builder.setNegativeButton("CLOSE APP" +
                "", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                finish();
            }
        });

        builder.setTitle("Permissions Required");
        builder.setMessage("Please enable all permissions");
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    //--check from here--//
    private void get_currentversion()
    {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            long firstinstalltime = packageInfo.firstInstallTime;
            long lastupdateime = packageInfo.lastUpdateTime;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            build_code = "sdk " + Build.VERSION.SDK_INT;
            versionname = String.valueOf(packageInfo.versionName);
            installedtime = dateFormat.format(new Date(firstinstalltime));
            updatedtime = dateFormat.format(new Date(lastupdateime));
            versioncode = String.valueOf(packageInfo.versionCode);
            // Toast.makeText(DashboardActivity.this,"shr_current_versionname = "+Preference.getInstance(this).getversionname(),Toast.LENGTH_LONG).show();
//                 Toast.makeText(LoginActivity.this,"current_versionname = "+jsonObject.getString("current_versionname"),Toast.LENGTH_LONG).show();
//                Toast.makeText(LoginActivity.this,"updated_time = "+jsonObject.getString("updated_time"),Toast.LENGTH_LONG).show();
                updateCurrentVerision();
        } catch (PackageManager.NameNotFoundException e) {
            //e.printStackTrace();
        }
    }
    private void updateCurrentVerision() {
        Map<String, String> params = new HashMap<>();
        params.put("reg_no",userEmail.getEditableText().toString());
        params.put("installed_time", installedtime);
        params.put("updated_time", updatedtime);
        params.put("current_versionname", versionname);
        params.put("current_versioncode", versioncode);
        params.put("build_code", build_code);
        MyRequestQueue myRequestQueue = MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.UPDATE_CURRENTVERSION, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                JSONObject json = null;
                try {
                    json = new JSONObject(response);
                    if (json != null) {
                        if (json.getInt("success") == 1) {
                            Preference preference = Preference.getInstance(RegisterActivity.this);
                            preference.putString("installed_time", installedtime);
                            preference.putString("updated_time", updatedtime);
                            preference.putString("current_versionname", versionname);
                            preference.putString("current_versioncode", versioncode);
                            preference.putString("build_code", build_code);
//                        Toast.makeText(getApplicationContext(),json.getString("message"),Toast.LENGTH_SHORT).show();
                            Toast.makeText(getApplicationContext(),json.getString("message"),Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
                            finish();
                        } else {
                         Toast.makeText(RegisterActivity.this,json.getString("message"),Toast.LENGTH_LONG).show();
                        }
                    }
                    else
                    {
                        Toast.makeText(RegisterActivity.this,"Please try again",Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(RegisterActivity.this,"Please try again",Toast.LENGTH_LONG).show();
                }


            }
        });
    }
}
