package com.example.leudaemialikeme.Activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.leudaemialikeme.Dao.FriendDao;
import com.example.leudaemialikeme.Dao.MessageDao;
import com.example.leudaemialikeme.Dao.OwnerDao;
import com.example.leudaemialikeme.Model.Friend;
import com.example.leudaemialikeme.Model.Message;
import com.example.leudaemialikeme.Model.Owner;
import com.example.leudaemialikeme.Model.User;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.litepal.LitePal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginActivity extends BaseActivity {
    private EditText edit_username;
    private EditText edit_pwd;
    private Button bt_login;
    private String username;
    private String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //获取数据库
        SQLiteDatabase db = LitePal.getDatabase();

        edit_username = findViewById(R.id.edit_username);
        edit_pwd = findViewById(R.id.edit_pwd);
        bt_login = findViewById(R.id.bt_login);

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = edit_username.getText().toString();
                pwd = edit_pwd.getText().toString();
                if(!username.equals("")&&!pwd.equals("")){
                    Map paramMap = new HashMap();
                    paramMap.put("username",username);
                    paramMap.put("password",pwd);
                    loginRequest(paramMap);
                }else {
                    Toast.makeText(LoginActivity.this, "用户名或密码格式错误!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void loginRequest(final Map paramMap){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = LoginActivity.SERVER_URL+"/main-servlet?action=login";
                    String jsonStr= OkHttpUtil.synPost(url, paramMap);
                    loginResponse(jsonStr,(String) paramMap.get("username"));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void loginResponse(final String jsonStr,final String username){
        runOnUiThread(new Runnable() {
            private OwnerDao ownerDao=new OwnerDao();
            @Override
            public void run() {
                if (jsonStr.equals("success")){
                    Owner dbOwner=ownerDao.findOwnerByUsername(username);
                    if (dbOwner!=null){
                        owner = dbOwner;
//                        ownerInfoSaveToPref(); //记住密码方法
//                        初始化WS链接
//                        System.out.println(owner);
                        initWebSocket(owner.getNetId());
                        Log.d("记录","开始获取未读信息");
                        getUnReadMsg();
                    }else{
                        //如果本地为空则说明是首次登录，则需要发送请求获取用户的个人信息及朋友列表数据存入本地数据库中，再进行存储
                        firstLoginRequest();
                    }
                }else{
                    Toast.makeText(LoginActivity.this, jsonStr, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //首次登录发送请求数据信息
    private void firstLoginRequest(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d("用户名",username);
                    String url = LoginActivity.SERVER_URL + "/main-servlet?action=firstLogin&username="+username;
                    String jsonStr= OkHttpUtil.synGet(url);
                    firstLoginResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void firstLoginResponse(final String jsonStr){
        runOnUiThread(new Runnable() {
            private OwnerDao ownerDao=new OwnerDao();
//            private FriendDao friendDao=new FriendDao();
            @Override
            public void run() {
                Gson gson = new Gson();
                Map<String, String> jsonMap= gson.fromJson(jsonStr,  new TypeToken <Map<String, String>>() {}.getType());
                final String message=(String) jsonMap.get("message");
                if (message.equals("success")){
                    //进行本地数据存储,本地数据库不存储密码，防止泄露，需要补全imageURL路径
//                    JSONObject data=(JSONObject) jsonMap.get("data");
//                    JSONObject netUser=(JSONObject) data.get("owner");
//                    JSONArray netFriends=(JSONArray) data.get("friends");
                    User user = gson.fromJson(jsonMap.get("user"), User.class);
                    //
                    Owner newOwner = new Owner();
                    newOwner.setUsername(user.getUsername());
                    newOwner.setPassword(user.getPassword());
                    newOwner.setNetId(user.getIduser());
//                    newOwner.setName(netUser.getString("name"));
//                    newOwner.setImageURL(SERVER_URL+netUser.getString("imagePath"));

                    ownerDao.insert(newOwner);  //插入本地数据库
                    //
//                    if (netFriends!=null && netFriends.size()>0){
//                        for (int i=0;i<netFriends.size();i++){
//                            JSONObject netFriend=(JSONObject) netFriends.get(i);
//                            String name=netFriend.getString("name");
//                            String imageUrl=SERVER_URL+netFriend.getString("imagePath");
//                            String username=netFriend.getString("username");
//                            int netId=netFriend.getInteger("id");
//                            Friend newFriend=new Friend(netId,username,name,imageUrl,newOwner.getNetId());
//                            friendDao.insert(newFriend);
//                        }
//                    }
                    owner = newOwner;
//                    ownerInfoSaveToPref();
                    //初始化WS链接
                    initWebSocket(owner.getNetId());
                    getUnReadMsg();
                }else{
                    Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //登录成功后获取未读消息
    private void getUnReadMsg(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = LoginActivity.SERVER_URL + "/main-servlet?action=getUnReadMsg&username="+username;
                    String jsonStr= OkHttpUtil.synGet(url);
                    Log.d("记录","未读信息获取响应");
                    getUnReadMsgResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getUnReadMsgResponse(final String jsonStr){
        runOnUiThread(new Runnable() {
            private MessageDao messageDao=new MessageDao();
            @Override
            public void run() {
                Gson gson = new Gson();
                Map<String, String> jsonMap= gson.fromJson(jsonStr, new TypeToken <Map<String, String>>() {}.getType());
                final String message=(String) jsonMap.get("message");
                if (message.equals("success")){
                    //进行本地消息存储
                    List<Message> msgList = gson.fromJson(jsonMap.get("msgList"), new TypeToken <List<Message>>() {}.getType());
                    for (int i=0;i<msgList.size();i++){
                        Message unReadMsg = msgList.get(i);
//                        System.out.println(unReadMsg.getSenderNetId());//////////////////////////////
                        String content = unReadMsg.getContent();
                        int messageType = unReadMsg.getMessageType();
                        int receiverId = unReadMsg.getReceiverNetId();
                        int senderId = unReadMsg.getSenderNetId();
                        Long createTime = unReadMsg.getCreateTime();
                        Message newMessage=new Message(senderId,receiverId,messageType,content,createTime);
                        messageDao.insert(newMessage);
                        getNewFriendRequest(senderId);
                        Log.d("记录","sender:"+senderId+" receiver:"+receiverId);
                    }
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }
    private void getNewFriendRequest(int senderId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = LoginActivity.SERVER_URL + "/main-servlet?action=getNewFriend&senderId="+senderId;
                    String jsonStr= OkHttpUtil.synGet(url);
                    getNewFriendResponse(jsonStr, senderId);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void getNewFriendResponse(String jsonStr, int senderId) {
        runOnUiThread(new Runnable() {
            private MessageDao messageDao=new MessageDao();
            @Override
            public void run() {
                Gson gson = new Gson();
                Map<String, String> jsonMap= gson.fromJson(jsonStr, new TypeToken <Map<String, String>>() {}.getType());
                final String message = jsonMap.get("message");
                if (message.equals("success")){
                    //进行本地消息存储
                    String username = jsonMap.get("username");
                    FriendDao friendDao = new FriendDao();
                    if(friendDao.findByNetId(senderId, owner.getNetId())==null){
                        Friend friend = new Friend(senderId, username, owner.getNetId());
                        friendDao.insert(friend);
                    }
                }
            }
        });
    }

}