package com.application.tak.takapplication;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
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.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
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.CreateClient;
import com.application.tak.takapplication.data_model.Adress;
import com.application.tak.takapplication.data_model.Client_V;
import com.application.tak.takapplication.data_model.User;
import com.application.tak.takapplication.interfaces.OnDBRequestFinished;
import com.application.tak.takapplication.local_db.LocalDB;
import com.application.tak.takapplication.services.LoginStatus;

import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    AutoCompleteTextView tvPassword;
    AutoCompleteTextView tvPhoneNo;
    AutoCompleteTextView tvUsername;
    AutoCompleteTextView tvCity;
    AutoCompleteTextView tvHouseNo;
    AutoCompleteTextView tvLastName;
    AutoCompleteTextView tvFirstName;
    AutoCompleteTextView tvPostCode;
    AutoCompleteTextView tvStreet;
    FloatingActionButton fab;
    ImageView imgView;
    Context _ctx;
    boolean userExists = true;
    boolean dataCorrect = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.act_clinet_login_details, container, false);

        _ctx = this.getContext();
        tvPassword = (AutoCompleteTextView) rootView.findViewById(R.id.regClientPassword);
        tvPhoneNo = (AutoCompleteTextView) rootView.findViewById(R.id.regClientPhoneNo);
        tvUsername = (AutoCompleteTextView) rootView.findViewById(R.id.regClientUsername);
        tvCity = (AutoCompleteTextView) rootView.findViewById(R.id.regClientCity);
        tvHouseNo = (AutoCompleteTextView) rootView.findViewById(R.id.regClientHouseNo);
        tvLastName = (AutoCompleteTextView) rootView.findViewById(R.id.regClientLName);
        tvFirstName = (AutoCompleteTextView) rootView.findViewById(R.id.regClientName);
        tvPostCode = (AutoCompleteTextView) rootView.findViewById(R.id.regClientPostCode);
        tvStreet = (AutoCompleteTextView) rootView.findViewById(R.id.regClientStreet);
        imgView = (ImageView) rootView.findViewById(R.id.imageView2);
        fab = (FloatingActionButton) rootView.findViewById(R.id.fabLoginMain);

        Config.LoggedInClient = new Client_V();
        Config.LoggedInClient.set_RoleId(2);
        Config.LoggedInClient.set_IsActive(0);

        Config.LoggedInClient.set_Adress(new Adress());
        fab.setVisibility(View.INVISIBLE);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((actClientLogin) getActivity()).SetCurrentItem(1);
            }
        });

        tvFirstName.addTextChangedListener(getTextWatcher(tvFirstName));
        tvLastName.addTextChangedListener(getTextWatcher(tvLastName));
        tvUsername.addTextChangedListener(getTextWatcher(tvUsername));
        tvPhoneNo.addTextChangedListener(getTextWatcher(tvPhoneNo));
        tvPassword.addTextChangedListener(getTextWatcher(tvPassword));
        tvStreet.addTextChangedListener(getTextWatcher(tvStreet));
        tvCity.addTextChangedListener(getTextWatcher(tvCity));
        tvPostCode.addTextChangedListener(getTextWatcher(tvPostCode));
        tvHouseNo.addTextChangedListener(getTextWatcher(tvHouseNo));

        View.OnFocusChangeListener focusChangedLstnr = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (!hasFocus) {
                    if (Config.LoggedInClient == null)
                        return;
                    if (view.equals(tvHouseNo)) {
                            Config.LoggedInClient.get_Adress().set_RoadNo(((AutoCompleteTextView) view).getText().toString());
                            view.setBackgroundColor(Color.TRANSPARENT);

                    }
                    if (view.equals(tvFirstName)) {
                        Config.LoggedInClient.set_FName(((AutoCompleteTextView) view).getText().toString());
                        view.setBackgroundColor(Color.TRANSPARENT);
                        if (Config.LoggedInClient.get_FName() != "" && Config.LoggedInClient.get_LName() != "" && Config.LoggedInClient.get_Username() == "") {
                            String username = Config.LoggedInClient.get_FName().toLowerCase() + "." + Config.LoggedInClient.get_LName().toLowerCase();
                            Config.LoggedInClient.set_Username(username);
                            tvUsername.setText(username);
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                        else if (tvFirstName.getText().length() <= 2)
                        {
                            TextViewValidate_String("Imię");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                    }
                    if (view.equals(tvLastName)) {
                        Config.LoggedInClient.set_LName(((AutoCompleteTextView) view).getText().toString(),3);
                        if (Config.LoggedInClient.get_FName() != "" && Config.LoggedInClient.get_LName() != "" && Config.LoggedInClient.get_Username() == "") {
                            String username = Config.LoggedInClient.get_FName().toLowerCase() + "." + Config.LoggedInClient.get_LName().toLowerCase();
                            Config.LoggedInClient.set_Username(username);
                            tvUsername.setText(username);
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                        else if (tvLastName.getText().length() < 1)
                        {
                            TextViewValidate_String("Nazwisko");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                    }
                    if (view.equals(tvCity)) {

                        if (tvCity.length() <= 2)
                        {
                            TextViewValidate_String("Miasto");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else {
                            Config.LoggedInClient.get_Adress().set_City(((AutoCompleteTextView) view).getText().toString());
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                    }
                    if (view.equals(tvPassword)) {
                        if(tvPassword.length() <= 3)
                        {
                            TextViewValidate_String("Hasło (co najmniej 4 znaki)");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else{
                        Config.LoggedInClient.set_Password(((AutoCompleteTextView) view).getText().toString());
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                    }
                    if (view.equals(tvPhoneNo)) {
                        if (tvPhoneNo.length() <= 8)
                        {
                            TextViewValidate_String("Telefon");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else
                            {

                        Config.LoggedInClient.set_PhoneNo(((AutoCompleteTextView) view).getText().toString());
                        view.setBackgroundColor(Color.TRANSPARENT);
                        }

                    }
                    if (view.equals(tvPostCode)) {
                        if (tvPostCode.length() <= 4)
                        {
                            TextViewValidate_String("Kod pocztowy, format 00-000");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else {
                            Config.LoggedInClient.get_Adress().set_PostCode(((AutoCompleteTextView) view).getText().toString());
                            tvPostCode.setText(Config.LoggedInClient.get_Adress().get_PostCode());
                            if(Config.LoggedInClient.get_Adress().get_PostCode() == "")
                            {
                                TextViewValidate_String("Kod pocztowy, format 00-000");
                                view.setBackgroundColor(Color.rgb(255,183,191));
                            }
                            else{
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                        }

                    }
                    if (view.equals(tvStreet)) {
                        if (tvStreet.length() <= 2)
                        {
                            TextViewValidate_String("Ulica");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else {

                            Config.LoggedInClient.get_Adress().set_Road(((AutoCompleteTextView) view).getText().toString());
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                    }
                    if (view.equals(tvUsername))
                    {
                        if (tvUsername.length() <= 2)
                        {
                            TextViewValidate_String("Ulica");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else{
                        Config.LoggedInClient.set_Username(((AutoCompleteTextView) view).getText().toString().trim());
                            view.setBackgroundColor(Color.TRANSPARENT);
                        if (!Config.LoggedInClient.get_Username().isEmpty())
                            CheckUsernameExistsInDB(Config.LoggedInClient.get_Username(),tvUsername);
                        }

                    }

                }
                CheckAllDataCorrect();




            }



        };


        //tvFirstName.setOnEditorActionListener(searchNextElLstnr);

        tvPhoneNo.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)) {
                    HideKeyboard();
                    ((actClientLogin) getActivity()).SetCurrentItem(1);
                }
                return false;
            }
        });


        if (tvHouseNo != null)
            tvHouseNo.setOnFocusChangeListener(focusChangedLstnr);


        if (tvFirstName != null)
            tvFirstName.setOnFocusChangeListener(focusChangedLstnr);

        if (tvLastName != null)
            tvLastName.setOnFocusChangeListener(focusChangedLstnr);

        if (tvPhoneNo != null) {
            //tvPhoneNo.setText("+48");
            //tvPhoneNo.setText(GetPhoneNo());
            //Config.LoggedInClient.set_PhoneNo(tvPhoneNo.getText().toString());
            tvPhoneNo.setOnFocusChangeListener(focusChangedLstnr);
        }

        if (tvPostCode != null)
            tvPostCode.setOnFocusChangeListener(focusChangedLstnr);

        if (tvCity != null)
            tvCity.setOnFocusChangeListener(focusChangedLstnr);

        if (tvStreet != null)
            tvStreet.setOnFocusChangeListener(focusChangedLstnr);

        if (tvPassword != null)
            tvPassword.setOnFocusChangeListener(focusChangedLstnr);

        if (tvUsername != null)
            tvUsername.setOnFocusChangeListener(focusChangedLstnr);

        if (imgView != null) {
            imgView.setVisibility(View.INVISIBLE);
            imgView.setEnabled(false);
        }

        return rootView;
    }

    private TextWatcher getTextWatcher(final EditText view) {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (view.equals(tvPostCode)) {
if(i==0 && i1==1 && i2==2)
{
    tvPostCode.append("-");

}
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (Config.LoggedInClient == null)
                    return;
                if (view.equals(tvHouseNo)) {
                    Config.LoggedInClient.get_Adress().set_RoadNo(((AutoCompleteTextView) view).getText().toString());
                    view.setBackgroundColor(Color.TRANSPARENT);

                }
                if (view.equals(tvFirstName)) {
                    Config.LoggedInClient.set_FName(((AutoCompleteTextView) view).getText().toString());
                    view.setBackgroundColor(Color.TRANSPARENT);
                    if (Config.LoggedInClient.get_FName() != "" && Config.LoggedInClient.get_LName() != "" && Config.LoggedInClient.get_Username() == "") {
                        String username = Config.LoggedInClient.get_FName().toLowerCase() + "." + Config.LoggedInClient.get_LName().toLowerCase();
                        Config.LoggedInClient.set_Username(username);
                        tvUsername.setText(username);
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                    else if (tvFirstName.getText().length() <= 2)
                    {
                       // TextViewValidate_String("Imię");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else if (Config.LoggedInClient.get_FName() != ""){
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
                if (view.equals(tvLastName)) {
                    Config.LoggedInClient.set_LName(((AutoCompleteTextView) view).getText().toString(),3);
                    if (Config.LoggedInClient.get_FName() != "" && Config.LoggedInClient.get_LName() != "" && Config.LoggedInClient.get_Username() == "") {
                        String username = Config.LoggedInClient.get_FName().toLowerCase() + "." + Config.LoggedInClient.get_LName().toLowerCase();
                        Config.LoggedInClient.set_Username(username);
                        tvUsername.setText(username);
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                    else if (tvLastName.getText().length() <= 2)
                    {
                        //TextViewValidate_String("Nazwisko");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else if (Config.LoggedInClient.get_LName() != ""){
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
                if (view.equals(tvCity)) {

                    if (tvCity.length() <= 2)
                    {
                        //TextViewValidate_String("Miasto");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else {
                        Config.LoggedInClient.get_Adress().set_City(((AutoCompleteTextView) view).getText().toString());
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
                if (view.equals(tvPassword)) {
                    if(tvPassword.length() <= 3)
                    {
                        //TextViewValidate_String("Hasło (co najmniej 4 znaki)");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else{
                        Config.LoggedInClient.set_Password(((AutoCompleteTextView) view).getText().toString());
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
                if (view.equals(tvPhoneNo)) {
                    if (tvPhoneNo.length() <= 8)
                    {
                        //TextViewValidate_String("Telefon");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else
                    {

                        Config.LoggedInClient.set_PhoneNo(((AutoCompleteTextView) view).getText().toString());
                        view.setBackgroundColor(Color.TRANSPARENT);
                        HideKeyboard();
                    }

                }
                if (view.equals(tvPostCode)) {
                    if (tvPostCode.length() <= 4)
                    {
                        //TextViewValidate_String("Kod pocztowy, format 00-000");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else {
                        Config.LoggedInClient.get_Adress().set_PostCode(((AutoCompleteTextView) view).getText().toString());
                        //tvPostCode.setText(Config.LoggedInClient.get_Adress().get_PostCode());
                        if(Config.LoggedInClient.get_Adress().get_PostCode() == "")
                        {
                            //TextViewValidate_String("Kod pocztowy, format 00-000");
                            view.setBackgroundColor(Color.rgb(255,183,191));
                        }
                        else{
                            view.setBackgroundColor(Color.TRANSPARENT);
                        }
                    }

                }
                if (view.equals(tvStreet)) {
                    if (tvStreet.length() <= 2)
                    {
                        //TextViewValidate_String("Ulica");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else {

                        Config.LoggedInClient.get_Adress().set_Road(((AutoCompleteTextView) view).getText().toString());
                        view.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
                if (view.equals(tvUsername))
                {
                    if (tvUsername.length() <= 2)
                    {
                        //TextViewValidate_String("Ulica");
                        view.setBackgroundColor(Color.rgb(255,183,191));
                    }
                    else{
                        Config.LoggedInClient.set_Username(((AutoCompleteTextView) view).getText().toString().trim());
                        view.setBackgroundColor(Color.TRANSPARENT);
                        if (!Config.LoggedInClient.get_Username().isEmpty())
                            CheckUsernameExistsInDB(Config.LoggedInClient.get_Username(),tvUsername);
                    }

                }

                CheckAllDataCorrect();
            }
        };
    }

    String GetPhoneNo() {
        String mPhoneNumber = "";
        try {
            TelephonyManager tMgr = (TelephonyManager) _ctx.getSystemService(Context.TELEPHONY_SERVICE);
            mPhoneNumber = tMgr.getLine1Number();
        }
        catch (SecurityException ex)
        {
            ex.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return mPhoneNumber;
    }

    void HideKeyboard()
    {
        View focused = getView();
        if (focused != null) {
            focused.clearFocus();
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(focused.getWindowToken(),0);
        }
    }

    void TextViewValidate_String(String tvName)
    {
        Toast.makeText(_ctx,"Błędnie uzupełnione pole: "+ tvName,Toast.LENGTH_LONG).show();
    }

    void CheckAllDataCorrect()
    {
        if(Config.LoggedInClient != null && Config.LoggedInClient.get_Adress() != null
                && !Config.LoggedInClient.get_Username().isEmpty()&&
                !Config.LoggedInClient.get_Password().isEmpty() &&
                !Config.LoggedInClient.get_LName().isEmpty() &&
                !Config.LoggedInClient.get_FName().isEmpty() &&
                !Config.LoggedInClient.get_Adress().get_City().isEmpty() &&
                !Config.LoggedInClient.get_Adress().get_PostCode().isEmpty() &&
                !Config.LoggedInClient.get_PhoneNo().isEmpty() &&
                !Config.LoggedInClient.get_Adress().get_Road().isEmpty())
        {
            dataCorrect = true;
        }
        else{
            dataCorrect = false;
        }

        if(dataCorrect)
        {
            //HideKeyboard();
            fab.setVisibility(View.VISIBLE);

        }
        else{
            fab.setVisibility(View.INVISIBLE);
        }
    }

    void CheckUsernameExistsInDB(String username, View v)
    {
        CheckUsernameExists checker = new CheckUsernameExists(username,_ctx,2);
        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)
                        {
                            userExists = true;
                            Config.LoggedInClient.set_Username("");
                            v.setBackgroundColor(Color.rgb(255,183,191));
                            Toast.makeText(_ctx,"Użytkownik o takim nicku już istnieje!",Toast.LENGTH_LONG).show();
                        }
                        else{
                            userExists = false;
                            v.setBackgroundColor(Color.TRANSPARENT);
                        }

                    }
                    else{
                        Config.LoggedInClient.set_Username("");
                        v.setBackgroundColor(Color.rgb(255,183,191));
                    }

                }
            }
        });
    }
}
