package com.avaya.sdksampleapp.commpackage;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.avaya.clientservices.unifiedportal.RequestToJoinMeetingCompletionHandler;
import com.avaya.clientservices.unifiedportal.UnifiedPortalError;
import com.avaya.clientservices.unifiedportal.UnifiedPortalMeetingInfo;

import static com.avaya.sdksampleapp.commpackage.SDKManager.CONFERENCE_URL;
import static com.avaya.sdksampleapp.commpackage.SDKManager.LOGIN_AS_GUEST;
import static com.avaya.sdksampleapp.commpackage.SDKManager.PASSWORD;
import static com.avaya.sdksampleapp.commpackage.SDKManager.USER_DISPLAY_NAME;
import static com.avaya.sdksampleapp.commpackage.SDKManager.USER_NAME;


/**
 * HTTPCallInitFragment is used to show call options available for the user and can be used to make outgoing audio\video call
 */
public class HTTPCallInitFragment extends Fragment implements View.OnClickListener {

    private static final String LOG_TAG = HTTPCallInitFragment.class.getSimpleName();

    private EditText conferenceUrl;
    private ToggleButton loginAsGuest;
    private EditText userDisplayName;
    private EditText userName;
    private EditText userPassword;
    private TextView errorMessage;
    private Button makeAudioCall;
    private Button makeVideoCall;

    private AboutFragment aboutFragment;

    private SDKManager sdkManagerInstance;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        // Get instance of SDKManager
        sdkManagerInstance = SDKManager.getInstance(getActivity());
    }

    @Override
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_about, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about:
                if (aboutFragment == null) {
                    aboutFragment = new AboutFragment();
                }
                getFragmentManager().beginTransaction().replace(R.id.dynamic_view, aboutFragment).addToBackStack(null).commit();
                break;
        }
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.http_call_init_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Initializing all controls on screen when it ready
        final TextView userDisplayNameLabel = (TextView) view.findViewById(R.id.user_display_name_label);
        final TextView userNameLabel = (TextView) view.findViewById(R.id.user_name_label);
        final TextView userPasswordLabel = (TextView) view.findViewById(R.id.user_password_label);
        conferenceUrl = (EditText) view.findViewById(R.id.conference_url);
        loginAsGuest = (ToggleButton) view.findViewById(R.id.login_as_guest);
        userDisplayName = (EditText) view.findViewById(R.id.user_display_name);
        userName = (EditText) view.findViewById(R.id.user_name);
        userPassword = (EditText) view.findViewById(R.id.user_password);
        makeAudioCall = (Button) view.findViewById(R.id.make_audio_call);
        makeVideoCall = (Button) view.findViewById(R.id.make_video_call);
        errorMessage = (TextView) view.findViewById(R.id.error_message);

        // Adding control listeners
        loginAsGuest.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean loginAsGuest){
                // Enable user display name editor if user joins a conference as guest
                userDisplayNameLabel.setEnabled(loginAsGuest);
                userDisplayName.setEnabled(loginAsGuest);

                // Enable user credentials editors if user joins a conference as signed in user
                userNameLabel.setEnabled(!loginAsGuest);
                userPasswordLabel.setEnabled(!loginAsGuest);
                userName.setEnabled(!loginAsGuest);
                userPassword.setEnabled(!loginAsGuest);
            }
        });
        makeAudioCall.setOnClickListener(this);
        makeVideoCall.setOnClickListener(this);

        // Updating controls with values saved in SharedPreferences
        SharedPreferences settings = getActivity().getSharedPreferences(SDKManager.CLIENTSDK_TEST_APP_PREFS, Context.MODE_PRIVATE);
        conferenceUrl.setText(settings.getString(CONFERENCE_URL, ""));
        loginAsGuest.setChecked(settings.getBoolean(LOGIN_AS_GUEST, false));
        userDisplayName.setText(settings.getString(USER_DISPLAY_NAME, getResources().getString(R.string.your_name_value)));
        userName.setText(settings.getString(USER_NAME, ""));
        userPassword.setText(settings.getString(PASSWORD, ""));
        // Note: Although this sample application manages passwords as clear text this application
        // is intended as a learning tool to help users become familiar with the Client SDK.
        // Managing passwords as clear text is not illustrative of a secure process to protect
        // passwords in an enterprise quality application.
    }

    @Override
    public void onClick(View view) {
        if (view == makeAudioCall || view == makeVideoCall) {

            // Collect information required to join conference
            final MeetingInfo meetingInfo = new MeetingInfo();
            meetingInfo.setConferenceURL(conferenceUrl.getText().toString());
            meetingInfo.loginAsGuest = loginAsGuest.isChecked();
            meetingInfo.userDisplayName = userDisplayName.getText().toString();
            meetingInfo.userName = userName.getText().toString();
            meetingInfo.password = userPassword.getText().toString();

            // Save meeting info in SharedPreferences
            SharedPreferences settings = getActivity().getSharedPreferences(SDKManager.CLIENTSDK_TEST_APP_PREFS, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(CONFERENCE_URL, meetingInfo.conferenceURL);
            editor.putBoolean(LOGIN_AS_GUEST, meetingInfo.loginAsGuest);
            editor.putString(USER_DISPLAY_NAME, meetingInfo.userDisplayName);
            editor.putString(USER_NAME, meetingInfo.userName);
            editor.putString(PASSWORD, meetingInfo.password);
            // Note: Although this sample application manages passwords as clear text this application
            // is intended as a learning tool to help users become familiar with the Client SDK.
            // Managing passwords as clear text is not illustrative of a secure process to protect
            // passwords in an enterprise quality application.
            editor.apply();

            // Start video call if the makeVideoCall button is pressed
            boolean isVideoCall = (view == makeVideoCall);

            makeCall(meetingInfo, isVideoCall, errorMessage);
            hideKeyboard(view);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void makeCall(final MeetingInfo meetingInfo, final boolean isVideoCall, final TextView errorMessage) {

        // Clear error state
        errorMessage.setText("");

        // Retrieve user token to join conference
        sdkManagerInstance.sendRequestToJoinMeeting(meetingInfo, new RequestToJoinMeetingCompletionHandler() {
            @Override
            public void onSuccess(UnifiedPortalMeetingInfo unifiedPortalMeetingInfo) {
                // Initializing callActiveFragment which will be used to show active call details
                CallActiveFragment callActiveFragment = new CallActiveFragment();

                CallWrapper callWrapper = sdkManagerInstance.createHTTPCall(meetingInfo, unifiedPortalMeetingInfo);

                Bundle bundle = new Bundle();
                bundle.putInt(SDKManager.CALL_ID, callWrapper.getCall().getCallId());
                bundle.putBoolean(SDKManager.IS_VIDEO_CALL, isVideoCall);
                callActiveFragment.setArguments(bundle);

                // Open active call fragment
                getFragmentManager().beginTransaction().replace(R.id.dynamic_view, callActiveFragment, SDKManager.ACTIVE_CALL_FRAGMENT_TAG).addToBackStack(null).commit();

                callWrapper.setVideoCall(isVideoCall);

                // Start the call
                sdkManagerInstance.startCall(callWrapper);
            }

            @Override
            public void onError(UnifiedPortalError e) {

                // Display error
                errorMessage.setText("Error: " + e.toString());
            }
        });
    }

    private void hideKeyboard(View view) {
        // Hide keyboard
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (!imm.isActive()) {
            return;
        }

        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        view.clearFocus();
    }

    @Override
    public void onResume() {
        super.onResume();

        // Set fragment title
        getActivity().setTitle(R.string.call_service);
    }
}