package com.example.share2;


import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;

import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.share2.fragment.HomePageActivity;
import com.example.share2.fragment.photo.GetPhotosList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String ACTION_REGISTER_START ="REGISTER" ;
    private EditText etPwd;
    private EditText etAccount;
    private TextView etSignUp;
    private CheckBox cbRemeberPwd;
    private ResponseBody<ResponseData> responseBody;
    private  Boolean bPwdSwitch = false;
    SharedPreferences sp;

    //启动某个界面的广播,这里应该是作为登录的广播，临时测试一下
    public class StartReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //测试用的为了不发起登录请求
            Intent intentRegister = new Intent(MainActivity.this, HomePageActivity.class);
            startActivity(intentRegister);
            //测试用的为了不发起登录请求
            if (responseBody != null){
                if(responseBody.getCode() == 200){
                     intentRegister = new Intent(MainActivity.this, HomePageActivity.class);
                    startActivity(intentRegister);
                    Log.d("ssssssss","xxxxxxxxx");
                }
                else {
                    Toast.makeText(MainActivity.this,responseBody.getMsg(),Toast.LENGTH_SHORT).show();
                }

            }
            else {
                Toast.makeText(MainActivity.this,"ssssssssss服务器错误！",Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.getSupportActionBar().hide();
        /*定义广播*/
        getResources();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_REGISTER_START);
        registerReceiver(new StartReceiver(), intentFilter);
        sp=getSharedPreferences("config", Context.MODE_PRIVATE);

        /*注册按钮*/
        etSignUp = findViewById(R.id.tv_sign_up);
        etSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentRegister = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intentRegister);
            }
        });


        /*密码切换明文密文*/
        final ImageView ivPwdSwitch = findViewById(R.id.iv_pwd_switch);
        ivPwdSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bPwdSwitch = !bPwdSwitch;
                if (bPwdSwitch) {
                    ivPwdSwitch.setImageResource(
                            R.drawable.ic_baseline_visibility_24);
                    etPwd.setInputType(
                            InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    ivPwdSwitch.setImageResource(
                            R.drawable.ic_baseline_visibility_off_24);
                    etPwd.setInputType(
                            InputType.TYPE_TEXT_VARIATION_PASSWORD |
                                    InputType.TYPE_CLASS_TEXT);
                    etPwd.setTypeface(Typeface.DEFAULT);
                }
            }
        });




        /*登录按钮*/
        etPwd = findViewById(R.id.et_pwd);
        etAccount = findViewById(R.id.et_account);
        cbRemeberPwd = findViewById(R.id.cb_remember_pwd);
        Button btLogin = findViewById(R.id.bt_login);
        btLogin.setOnClickListener(this);

        /*记住密码*/
        String spFileName = getResources().getString(R.string.share_preferences_file);
        String accountKey = getResources().getString(R.string.login_account_name);
        String passwordKey = getResources().getString(R.string.login_password);
        String remeberPasswordKey = getResources().getString(R.string.login_remeber_password);

        SharedPreferences spFile = getSharedPreferences(spFileName, Context.MODE_PRIVATE);

        String account = spFile.getString(accountKey, null);
        String password = spFile.getString(passwordKey, null);
        Boolean remeberPassword = spFile.getBoolean(remeberPasswordKey,false);
        if(account != null && !TextUtils.isEmpty(account)){
            etAccount.setText(account);
        }
        if(password != null && !TextUtils.isEmpty(password)){
            etPwd.setText(password);
        }
        cbRemeberPwd.setChecked(remeberPassword);


    }


    public void onClick(View view) {
        String spFileName = getResources().getString(R.string.share_preferences_file);
        String accountKey = getResources().getString(R.string.login_account_name);
        String passwordKey = getResources().getString(R.string.login_password);
        String remeberPasswordKey = getResources().getString(R.string.login_remeber_password);

        SharedPreferences spFile = getSharedPreferences(spFileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = spFile.edit();

        if(cbRemeberPwd.isChecked()){
            String password = etPwd.getText().toString();
            String account = etAccount.getText().toString();

            editor.putString(accountKey, account);
            editor.putString(passwordKey, password);
            editor.putBoolean(remeberPasswordKey, true);
            editor.apply();
        }else {
            editor.remove(accountKey);
            editor.remove(passwordKey);
            editor.remove(remeberPasswordKey) ;
            editor.apply();
        }
        try {
            this.Login();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void Login() throws ClassNotFoundException {


        ConnectServer connectServer = new ConnectServer();
        Headers headers = connectServer.getHeaders(new HashMap<>());

        String username = etAccount.getText().toString();
        String password = etPwd.getText().toString();

        FormBody.Builder builder_body = new FormBody.Builder();
        builder_body.add("username",username);
        builder_body.add("password",password);
        FormBody formBody = builder_body.build();
        //测试用的为了不发起登录请求
//        Intent musicStartIntent = new Intent(MainActivity.ACTION_REGISTER_START);
//        sendBroadcast(musicStartIntent);

        //测试用的为了不发起登录请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(Constants.SERVER_URL+Constants.USER_LOGIN).
                headers(headers).method("POST",formBody).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("Fail","请求失败了");
                Intent musicStartIntent = new Intent(MainActivity.ACTION_REGISTER_START);
                sendBroadcast(musicStartIntent);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    final String body = response.body().string();
                    System.out.println(body);
                    Gson gson1 = new Gson();
                    Type jsonType = new TypeToken<ResponseBody<ResponseData>>(){}.getType();
                    responseBody = gson1.fromJson(body,jsonType);
                    ResponseData data = responseBody.getData();
                    if (responseBody.getCode()==200){
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("username",data.getUsername());
                        edit.putString("id",data.getId());

                        if (data.getAvatar()!=null){
                            edit.putString("avatar",data.getAvatar());
                        }
                        else {
                            edit.putString("avatar","");
                        }
                        if (data.getSex()!=null){
                            edit.putString("sex",data.getSex());
                        }
                        else {
                            edit.putString("sex","");
                        }
                        if (data.getIntroduce()!=null){
                            edit.putString("introduce",data.getIntroduce());
                        }
                        else {
                            edit.putString("introduce","");
                        }
                        edit.apply();
                        Intent musicStartIntent = new Intent(MainActivity.ACTION_REGISTER_START);
                        sendBroadcast(musicStartIntent);
                    }


                }

            }
        });
    }

}