package com.application.tak.takapplication;

import android.content.Context;
import android.content.Intent;
import android.opengl.Visibility;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.application.tak.takapplication.data_access.CheckUsernameExists;
import com.application.tak.takapplication.data_access.Config;
import com.application.tak.takapplication.data_access.CreateStudent;
import com.application.tak.takapplication.data_model.User;
import com.application.tak.takapplication.interfaces.OnDBRequestFinished;
import com.application.tak.takapplication.services.LoginStatus;

import java.util.regex.Pattern;

/**
 * Created by Aleksandra on 04.05.2017.
 */
public class actStudentLoginDetails  extends Fragment {

    Context ctx;
    AutoCompleteTextView phone;
    AutoCompleteTextView email;
    boolean usernameExists = true;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.act_student_login_details, container, false);

        ctx = this.getContext();
        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabGoToStudentTaSK);
        fab.setVisibility(View.INVISIBLE);


        RadioButton rb = (RadioButton) rootView.findViewById(R.id.rbRegulaminAccept);
        rb.setChecked(false);
        rb.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {

                RadioButton rb = (RadioButton) rootView.findViewById(R.id.rbRegulaminAccept);
                FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabGoToStudentTaSK);
                if (rb.isChecked())
                {
                    //fab.show();
                    ((actStudentLogin)getActivity()).regulationAccepted = true;
                    ((actStudentLogin)getActivity()).SetCurrentItem(3);

                }
            }
        });

        AutoCompleteTextView regulamin = (AutoCompleteTextView) rootView.findViewById(R.id.regulamin);
        regulamin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(view.getContext(), actStudentRegulation.class);
                startActivity(i);

            }
        });

       phone = (AutoCompleteTextView) rootView.findViewById(R.id.phone_input);
       //phone.setText("+48");

   phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
       @Override
       public void onFocusChange(View v, boolean hasFocus) {
           if(!hasFocus)
           {
               phone.setHint("");
               SetPhoneNo();
           }
           else{
               phone.setHint("telefon");
           }
       }
   });

   phone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_NEXT))
                {
                    email.findFocus();
                }
                return false;
            }
        });



        email = (AutoCompleteTextView) rootView.findViewById(R.id.email_input);

        if(Config.LoggedInStudent != null)
            email.setText(Config.LoggedInStudent.get_Username());
        email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    email.setHint("e-mail");
                else
                {
                    email.setHint("");
                    SetEmail();
                }
            }
        });

        email.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE))
                {
                    rb.findFocus();
                }
                return false;
            }
        });

        return rootView;
    }


void SetPhoneNo()
    {
        if(CheckPhoneNoCorrect(phone.getText().toString()) && Config.LoggedInStudent != null)
        {
            Config.LoggedInStudent.set_PhoneNo(phone.getText().toString().trim());
        }
        else if(Config.LoggedInStudent != null)
        {
            Config.LoggedInStudent.set_PhoneNo("");
        }
        else{
            ((actStudentLogin)getActivity()).SetCurrentItem(0);
        }
    }

    void SetEmail()
    {
        if(CheckEmailCorrect(email.getText().toString()) && Config.LoggedInStudent != null)
        {
            CheckUsernameExists(email.getText().toString().trim());
        }
        else if(Config.LoggedInStudent != null)
        {
            Config.LoggedInStudent.set_Username("");
        }
        else{
            ((actStudentLogin)getActivity()).SetCurrentItem(0);
        }
    }


    boolean CheckPhoneNoCorrect(String text)
    {

        if(Pattern.matches("^\\d{9}$", text))
        {
            return true;
        }

        Toast.makeText(ctx,"Nieprawidłowy nr telefonu!",Toast.LENGTH_LONG).show();
        return false;
    }

    boolean CheckEmailCorrect(String text)
    {
        text = text.trim();
        if(text.contains("@") && !text.startsWith("@") && !text.endsWith("@") && !text.contains(" ") && text.contains("."))
        {
            return true;
        }

        Toast.makeText(ctx,"Nieprawidłowy email!",Toast.LENGTH_LONG).show();
        return false;
    }

    void CheckUsernameExists(String username)
    {
        if(Config.LoggedInStudent == null)
        {
            ((actStudentLogin)getActivity()).SetCurrentItem(0);
        return;
        }
        CheckUsernameExists checker = new CheckUsernameExists(username,ctx,-1);
        checker.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished() {
                if(checker.dbResult != null )
                {
                    String msg = checker.dbResult.getMSG();
                    if(msg.contentEquals("Sukces"))
                    {
                        if(checker.dbResult.getRESULT() > 0)
                        {

                            Toast.makeText(ctx,"W bazie istnieje już podany email!",Toast.LENGTH_LONG).show();
                            Config.LoggedInStudent.set_Username("");
                        }
                        else{

                            Config.LoggedInStudent.set_Username(username);
                        }

                    }
                }
            }
        });
    }
}