package com.virjar.echo.adr.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.virjar.echo.adr.R;
import com.virjar.echo.adr.bean.Result;
import com.virjar.echo.adr.bean.UserInfo;
import com.virjar.echo.adr.repo.APIServices;
import com.virjar.echo.adr.repo.EchoConfig;
import com.virjar.echo.nat.log.EchoLogger;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    ImageView imageView;
    TextView textView;
    int count = 0;
    private Button buttonLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);

        setupAnimation();

        Button btnSetting = findViewById(R.id.btn_setting);
        btnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SettingsActivity.go(LoginActivity.this);
            }
        });

        autoLoginWithToken();

        // bind login button event
        final EditText editTextUsername = findViewById(R.id.edt_username);
        final EditText editTextPassword = findViewById(R.id.edt_password);
        buttonLogin = findViewById(R.id.btn_sign_in);
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = editTextUsername.getText().toString();
                if (userName.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "please input username", Toast.LENGTH_SHORT).show();
                    return;
                }
                String password = editTextPassword.getText().toString();
                if (password.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "please input password", Toast.LENGTH_SHORT).show();
                    return;
                }
                loginWithUserName(userName, password);
            }
        });


    }

    private void autoLoginWithToken() {
        String token = EchoConfig.getToken();
        if (TextUtils.isEmpty(token)) {
            autoLoginWithUserName();
            return;
        }
        Call<Result<UserInfo>> loginResponse = APIServices.userApi.loginWithToken();
        loginResponse.enqueue(new Callback<Result<UserInfo>>() {
            @Override
            public void onResponse(Call<Result<UserInfo>> call, Response<Result<UserInfo>> response) {
                Result<UserInfo> body = response.body();
                if (!body.isOk()) {
                    EchoLogger.getLogger().info("auto login with token failed: " + body.getErrorMessage());
                    autoLoginWithUserName();
                } else {
                    EchoLogger.getLogger().info("auto login with token success");
                    onLoginSuccess(body.getData());
                }
            }

            @Override
            public void onFailure(Call<Result<UserInfo>> call, Throwable t) {
                EchoLogger.getLogger().error("auto login with token failed", t);
                autoLoginWithUserName();
            }
        });
    }


    private void autoLoginWithUserName() {
        String username = EchoConfig.getUsername();
        String password = EchoConfig.getPassword();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            EchoLogger.getLogger().info("no user name cached,skip auto login with username");
            return;
        }
        loginWithUserName(username, password);
    }

    private void loginWithUserName(String username, String password) {
        buttonLogin.setClickable(false);
        APIServices.userApi
                .loginWithUsername(username, password)
                .enqueue(new Callback<Result<UserInfo>>() {
                    @Override
                    public void onResponse(Call<Result<UserInfo>> call, Response<Result<UserInfo>> response) {
                        buttonLogin.setClickable(true);
                        final Result<UserInfo> result = response.body();
                        if (!result.isOk()) {
                            EchoLogger.getLogger().error("login failed:" + result.getErrorMessage());
                            LoginActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, result.getErrorMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                            return;
                        }
                        onLoginSuccess(result.getData());
                    }

                    @Override
                    public void onFailure(Call<Result<UserInfo>> call, Throwable t) {
                        buttonLogin.setClickable(true);
                        EchoLogger.getLogger().error("auto login with username failed", t);
                    }
                });
    }


    private void onLoginSuccess(UserInfo userInfo) {
        EchoConfig.updateLoginToken(userInfo.getLoginToken());
        EchoConfig.saveUsernameAndPassword(userInfo.getAccount(), userInfo.getPassword());
        MainActivity.go(this);
        finish();
    }

    private void setupAnimation() {
        imageView.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
            public void onSwipeTop() {
            }

            public void onSwipeRight() {
                if (count == 0) {
                    imageView.setImageResource(R.drawable.good_night_img);
                    textView.setText("Night");
                    count = 1;
                } else {
                    imageView.setImageResource(R.drawable.good_morning_img);
                    textView.setText("Morning");
                    count = 0;
                }
            }

            public void onSwipeLeft() {
                if (count == 0) {
                    imageView.setImageResource(R.drawable.good_night_img);
                    textView.setText("Night");
                    count = 1;
                } else {
                    imageView.setImageResource(R.drawable.good_morning_img);
                    textView.setText("Morning");
                    count = 0;
                }
            }

            public void onSwipeBottom() {
            }

        });
    }

}
