package org.linphone.bluereach;
/*
LoginFragment.java
Copyright (C) 2017  Belledonne Communications, Grenoble, France

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;


import org.json.JSONException;
import org.json.JSONObject;
import org.linphone.R;
import org.linphone.rest.AsyncHttpResponse;
import org.linphone.rest.RestApis;
import org.linphone.utils.AppMethods;
import org.linphone.utils.AppStrings;
import org.linphone.utils.SecondSessionManager;
import org.linphone.utils.SessionManager;

import java.util.ArrayList;

public class LoginFragment extends Fragment implements OnClickListener, AsyncHttpResponse.AsyncHttpResponseListener {
    private EditText login, userid, password, domain, displayName;
    private RadioGroup transports;
    private Button apply;


    EditText signin_phone_et, signin_password_et;
    TextView signin_tv, signin_forgot_pwd_tv, signin_signup_tv;
   // LinphoneAddress.TransportType transport;
    Intent intent;
    SessionManager sm;
    SecondSessionManager secondSessionManager;
    private static final String TAG = "LoginFragment";


    ProgressDialog pd;
    ImageView back_iv;
    LinearLayout already_register_ll;

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

		/*login = (EditText) view.findViewById(org.bluereachconnect.R.id.assistant_username);
        login.addTextChangedListener(this);
		displayName = (EditText) view.findViewById(org.bluereachconnect.R.id.assistant_display_name);
		displayName.addTextChangedListener(this);
		userid = (EditText) view.findViewById(org.bluereachconnect.R.id.assistant_userid);
		userid.addTextChangedListener(this);
		password = (EditText) view.findViewById(org.bluereachconnect.R.id.assistant_password);
		password.addTextChangedListener(this);
		domain = (EditText) view.findViewById(org.bluereachconnect.R.id.assistant_domain);
		domain.addTextChangedListener(this);
		transports = (RadioGroup) view.findViewById(org.bluereachconnect.R.id.assistant_transports);
		apply = (Button) view.findViewById(org.bluereachconnect.R.id.assistant_apply);
		apply.setEnabled(false);
		apply.setOnClickListener(this);*/

        init(view);

        return view;
    }


    public void init(View view) {
        sm = new SessionManager(getActivity());
        secondSessionManager = new SecondSessionManager(getActivity());
        signin_phone_et = (EditText) view.findViewById(R.id.signin_phone_et);
        signin_password_et = (EditText) view.findViewById(R.id.signin_password_et);

        signin_tv = (TextView) view.findViewById(R.id.signin_tv);
        signin_forgot_pwd_tv = (TextView) view.findViewById(R.id.signin_forgot_pwd_tv);
        signin_signup_tv = (TextView) view.findViewById(R.id.signin_signup_tv);
        back_iv = (ImageView) view.findViewById(R.id.back_iv);
        already_register_ll = (LinearLayout) view.findViewById(R.id.already_register_ll);

        signin_tv.setOnClickListener(this);
        signin_forgot_pwd_tv.setOnClickListener(this);
        signin_signup_tv.setOnClickListener(this);
        back_iv.setOnClickListener(this);
        already_register_ll.setOnClickListener(this);

        settingOldCredentials();
        //transport = LinphoneAddress.TransportType.LinphoneTransportTls;


        if (sm.getBooleanData(AppStrings.Session.is_login)) {
            already_register_ll.setVisibility(View.GONE);
            signin_forgot_pwd_tv.setVisibility(View.GONE);
            back_iv.setVisibility(View.VISIBLE);
        } else {
            if (sm.getBooleanData(AppStrings.Session.is_login)) {
                already_register_ll.setVisibility(View.VISIBLE);
                signin_forgot_pwd_tv.setVisibility(View.VISIBLE);
                back_iv.setVisibility(View.GONE);
            }
        }
    }

    public void validation() {
        if (signin_phone_et.getText().toString().isEmpty()) {
            AppMethods.alertWithOk(getActivity(), getActivity().getResources().getString(R.string.enter_number));
        } else if (signin_password_et.getText().toString().isEmpty()) {
            AppMethods.alertWithOk(getActivity(), getActivity().getResources().getString(R.string.enter_password));
        } else {
            //checkLocationPermission();


        }
    }
    public  void redirection(){

        if (!AppMethods.checkGpsOnOff(getActivity())) {
            AppMethods.ShowGpsAlert(getActivity(), getString(R.string.alert_enable_gps), "");
            AppMethods.startLocationService(getActivity());
        } else {
            signinApi();
        }
/*
        if (AppMethods.checkingLocationPermissions(getActivity())) {
//            startLocationService();
            if (!AppMethods.checkGpsOnOff(getActivity())) {
                AppMethods.ShowGpsAlert(getActivity(), getString(R.string.alert_enable_gps), "");
                AppMethods.startLocationService(getActivity());
            } else {
                signinApi();
            }
        } else {
            AppMethods.checkingLocationPermissions(getActivity());
        }
*/

    }
  /*  public void checkLocationPermission(){
        PermissionListener permissionlistener = new PermissionListener() {
            @Override
            public void onPermissionGranted() {
                redirection();
            }

            @Override
            public void onPermissionDenied(ArrayList<String> deniedPermissions) {
//                Toast.makeText(activity, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
                redirection();
            }
        };
        TedPermission.with(getActivity())
                .setPermissionListener(permissionlistener)
                .setPermissions(Manifest.permission.ACCESS_FINE_LOCATION)
                .check();


    }*/
    public void signinApi() {


        Log.e(TAG, "signinApi: "+signin_phone_et.getText().toString() );
        Log.e(TAG, "signinApi: "+signin_password_et.getText().toString() );
        if (AppMethods.isConnectingToInternet(getActivity())) {
            AsyncHttpResponse response = new AsyncHttpResponse(this, true);
            JSONObject jo = null;
            try {
                jo = new JSONObject();
                jo.put(AppStrings.InputParams.action, RestApis.login);
                JSONObject job = new JSONObject();
                job.put(AppStrings.InputParams.PhoneNumber, signin_phone_et.getText().toString());
                job.put(AppStrings.InputParams.Password, signin_password_et.getText().toString());
                jo.put(AppStrings.InputParams.params, job);
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.postJsonAsyncHttp(RestApis.url, RestApis.login, jo);
        } else {
            AppMethods.alertForNoInternet(getActivity());
        }
    }

    public void signinResponse(String response) {

        Log.e(TAG, "signinResponse: response is : "+response );
        try {
            JSONObject jo = new JSONObject(response);
            String Status = jo.optString(AppStrings.OutputParams.Status);
            String Message = jo.optString(AppStrings.OutputParams.Message);
            if (Status.equals(AppStrings.OutputParams.Success)) {
                String userdetails = jo.optString(AppStrings.OutputParams.userdetails);
                JSONObject job = new JSONObject(userdetails);
                String OTP = job.optString(AppStrings.OutputParams.OTP);
                String FirstName = job.optString(AppStrings.OutputParams.FirstName);
                String LastName = job.optString(AppStrings.OutputParams.LastName);
                String EmailID = job.optString(AppStrings.OutputParams.EmailID);
                String PhoneNumber = job.optString(AppStrings.OutputParams.PhoneNumber);
                String Password = job.optString(AppStrings.OutputParams.Password);
                String userID = job.optString(AppStrings.OutputParams.userID);
                String OtpVerificationStatus = job.optString(AppStrings.OutputParams.OtpVerificationStatus);
                sm.createUserLoginSession();
                sm.setStoreData(AppStrings.Session.login, userID);
                sm.setStoreData(AppStrings.Session.password, Password);
                Log.e(TAG, "signinResponse:1233 "+sm.getStoreData(AppStrings.Session.login) );
                Log.e(TAG, "signinResponse:12345 "+sm.getStoreData(AppStrings.Session.password) );
               /* AssistantActivity.instance().genericLogIn(userID, "", Password, "", null,
                        getResources().getString(R.string.sipaddress), transport);
*/
                sm.setBooleanData(AppStrings.Session.is_login, true);
                secondSessionManager.setUsername(PhoneNumber);
                secondSessionManager.setPassword(Password);

            } else {
                AppMethods.alertWithOk(getActivity(), Message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.signin_tv:

			 /*checking validation and performing login*/

                validation();

                break;
            case R.id.back_iv:
                getActivity().finish();
                break;
            case R.id.signin_forgot_pwd_tv:

				/* redirecting to Forgot password screen*/

                //startActivity(new Intent(getActivity(), ForgotPassword.class));


                break;
            case R.id.signin_signup_tv:


				/* First redirecting to Assistant activity then SignUp Screen */
               // AssistantActivity.instance().changingSignupFagment();

                break;
        }
    }

    @Override
    public void onAsyncHttpResponseGet(String response, String URL) throws JSONException {
        if (URL.equals(RestApis.login)) {
            signinResponse(response);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult:requestCode is :  " + requestCode);
        Log.e(TAG, "onActivityResult:resultCode is :  " + resultCode);
        Log.e(TAG, "onActivityResult:data is :  " + data);


//        if (resultCode == AppIntegers.signup_frag) {
        if (resultCode == 3) {
            if (data != null) {


                Log.e(TAG, "onActivityResult: is :  " + data.getStringExtra("user_name"));


                //LinphoneAddress.TransportType transport = LinphoneAddress.TransportType.LinphoneTransportTls;

           /*     AssistantActivity.instance().genericLogIn(data.getStringExtra("user_name"), "", data.getStringExtra("password"), "", null,
                        getActivity().getResources().getString(R.string.sipaddress), transport);*/

            }
        }

    }



    public void settingOldCredentials() {
        try {
            if (!secondSessionManager.getUsername().equals("") || secondSessionManager.getPassword().equals("")) {
                signin_phone_et.setText(secondSessionManager.getUsername());
                signin_password_et.setText(secondSessionManager.getPassword());
            }

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

    }

	/*@Override
	public void onClick(View v) {
		int id = v.getId();

		if (id == org.bluereachconnect.R.id.assistant_apply) {
			if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0 || domain.getText() == null || domain.length() == 0) {
				Toast.makeText(getActivity(), getString(org.bluereachconnect.R.string.first_launch_no_login_password), Toast.LENGTH_LONG).show();
				return;
			}

			TransportType transport;
			if(transports.getCheckedRadioButtonId() == org.bluereachconnect.R.id.transport_udp){
				transport = TransportType.LinphoneTransportUdp;
			} else {
				if(transports.getCheckedRadioButtonId() == org.bluereachconnect.R.id.transport_tcp){
					transport = TransportType.LinphoneTransportTcp;
				} else {
					transport = TransportType.LinphoneTransportTls;
				}
			}

			if (domain.getText().toString().compareTo(getString(org.bluereachconnect.R.string.default_domain)) == 0) {
				AssistantActivity.instance().displayLoginLinphone(login.getText().toString(), password.getText().toString());
			} else {
				AssistantActivity.instance().genericLogIn(login.getText().toString(), userid.getText().toString(), password.getText().toString(), displayName.getText().toString(), null, domain.getText().toString(), transport);
			}
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		apply.setEnabled(!login.getText().toString().isEmpty() && !password.getText().toString().isEmpty() && !domain.getText().toString().isEmpty());
	}

	@Override
	public void afterTextChanged(Editable s) {

	}*/
}
