package kr.co.icontrols.iotplatform;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserDetails;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GetDetailsHandler;

import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.Mqtt.MqttController;
import kr.co.icontrols.iotplatform.cognito.AppHelper;
import kr.co.icontrols.iotplatform.cognito.ItemToDisplay;
import kr.co.icontrols.iotplatform.utils.DownloadImageTask;
import kr.co.icontrols.iotplatform.utils.GetSessionCallback;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.cancelToExit;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getCognitoSession;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.isExpiredSession;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.isRestartAppForBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.resetBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.restartApp;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.setBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.COGNITO_NICKNAME;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CALL_CENTER;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_UPDATE_DATA;

public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG="ProfileActivity";

    private TextView txtName, txtLocation;

    private AlertDialog userDialog;
    private ProgressDialog waitDialog;

    // Cognito user objects
    private CognitoUser user;
    private CognitoUserSession session;
    private CognitoUserDetails details;

    // User details
    private String username;

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

        txtName = findViewById(R.id.txtName);
        txtLocation = findViewById(R.id.txtLocation);

        // Get the user name
        Bundle extras = getIntent().getExtras();
        username = AppHelper.getCurrUser();
        user = AppHelper.getPool().getUser(username);

        setUi();
    }

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

        if(isRestartAppForBackgroundWaitTime()) {
            restartApp(this);
            return;
        }

        if(isExpiredSession()) {
            getCognitoSession(new GetSessionCallback() {
                @Override
                public void successed() {
                    getDetails();
                }

                @Override
                public void failed() {
                    showNotiMsg(ProfileActivity.this, "세션을 갱신하지 못하였습니다.");
                    System.exit(0);
                }
            });
        } else {
            getDetails();
        }
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        cancelToExit(this);
    }

    @Override
    protected void onPause() {
        setBackgroundWaitTime();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        resetBackgroundWaitTime();
        super.onDestroy();
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_UPDATE_DATA:
                if(resultCode == RESULT_OK) {
                    setUi();
                }
                break;
            case RESULT_CALL_CENTER:
                if(resultCode == RESULT_OK) {
                    Intent intent = new Intent(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + getString(R.string.service_center_hp)));
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        /*
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);
        */

        if(!UserInfo.confirmed && (v.getId() != R.id.btnEditUser)) {
            showNotiMsg(this, "인증 후 사용 가능합니다.");
            return;
        }

        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnEditUser:
                startActivityForResult(new Intent(this,ProfileUserActivity.class),RESULT_UPDATE_DATA);
                break;
            case R.id.layoutLocation:
                startActivity(new Intent(this,RegisterLocationActivity.class));
                break;
            case R.id.layoutMember:
                startActivity(new Intent(this,AdminMemberActivity.class));
                break;
            case R.id.layoutSwitchMapper:
                startActivity(new Intent(this,SwitchMapperRegisterGuideActivity.class));
                break;
            case R.id.layoutSetting:
                startActivity(new Intent(this,SettingActivity.class));
                break;
            case R.id.layoutFaq:
                startActivity(new Intent(this,FaqActivity.class));
                break;
            case R.id.layoutNoti:
                startActivity(new Intent(this,NotificationActivity.class));
                break;
            case R.id.txtCallCenter: {
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_YESNO);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.popup_call_center));
                intent.putExtra(PopupActivity.POPUP_OK_BUTTON_TEXT, getString(R.string.call));
                startActivityForResult(intent, RESULT_CALL_CENTER);
                }
                break;
            case R.id.btnGoToMall: {
                Uri uriUrl = Uri.parse("https://bestin.hdc-smart.com/main/index");
                Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
                startActivity(launchBrowser);
                }
                break;
            case R.id.txtKakao: {
                Uri uriUrl = Uri.parse("https://pf.kakao.com/_yxmPxbxb/chat");
                Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
                startActivity(launchBrowser);
                }
                break;
        }
    }


    private void setUi() {
        // show The Image in a ImageView
        if(UserInfo.profile != null && !UserInfo.profile.isEmpty()) {
            new DownloadImageTask(findViewById(R.id.imgProfile)).execute(UserInfo.profile);
        } else {
            ((ImageView)findViewById(R.id.imgProfile)).setImageResource(R.drawable.profile_thum_176);
        }

        if(UserInfo.nickname != null && !UserInfo.nickname.isEmpty()) {
            txtName.setText(UserInfo.nickname);
        }

        if(UserInfo.location != null && UserInfo.location.size() > 0) {
            txtLocation.setText(UserInfo.location.get(0).address.city + " " + UserInfo.location.get(0).address.district +" " + UserInfo.location.get(0).address.town);
        } else {
            ((TextView)findViewById(R.id.txtLocation)).setText(getString(R.string.hint_input_location));
        }
    }

    // Get user details from CIP service
    private void getDetails() {
        AppHelper.getPool().getUser(username).getDetailsInBackground(detailsHandler);
    }

    // Show user attributes from CIP service
    private void showAttributes() {
        int count = AppHelper.getItemCount();
        for(int i = 0 ; i < count ; i++) {
            ItemToDisplay it = AppHelper.getItemForDisplay(i);
            if(it.getLabelText().equals(COGNITO_NICKNAME)) {
                //txtName.setText(it.getDataText());
            }
        }
    }

    GetDetailsHandler detailsHandler = new GetDetailsHandler() {
        @Override
        public void onSuccess(CognitoUserDetails cognitoUserDetails) {
            closeWaitDialog();
            // Store details in the AppHandler
            AppHelper.setUserDetails(cognitoUserDetails);
            showAttributes();
        }

        @Override
        public void onFailure(Exception exception) {
            closeWaitDialog();
            showDialogMessage("Could not fetch user details!", AppHelper.formatException(exception), true);
        }
    };

    GenericHandler trustedDeviceHandler = new GenericHandler() {
        @Override
        public void onSuccess() {
            // Close wait dialog
            closeWaitDialog();
        }

        @Override
        public void onFailure(Exception exception) {
            closeWaitDialog();
            showDialogMessage("Failed to update device status", AppHelper.formatException(exception), true);
        }
    };

    private void updateDeviceStatus(CognitoDevice device) {
        device.rememberThisDeviceInBackground(trustedDeviceHandler);
    }

    private void showDialogMessage(String title, String body, final boolean exit) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title).setMessage(body).setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    userDialog.dismiss();
                    if(exit) {
                        exit();
                    }
                } catch (Exception e) {
                    // Log failure
                    Log.e(TAG," -- Dialog dismiss failed");
                    if(exit) {
                        exit();
                    }
                }
            }
        });
        userDialog = builder.create();
        userDialog.show();
    }

    private void closeWaitDialog() {
        try {
            waitDialog.dismiss();
        }
        catch (Exception e) {
            //
        }
    }

    private void exit () {
        Intent intent = new Intent();
        if(username == null)
            username = "";
        intent.putExtra("name",username);
        setResult(RESULT_OK, intent);
        finish();
    }
}