package com.example.leudaemialikeme.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.leudaemialikeme.Adapter.QuestionDetailAdapter;
import com.example.leudaemialikeme.Model.AnswerItemView;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class QuestionDetailActivity extends AppCompatActivity {
    private ImageView question_back;
    private ImageView detail_to_search;
    private TextView text_question_title;
    private TextView text_author;
    private TextView text_question_content;
    private ImageView img_invite_to_answer;
    private ImageView img_go_write_answer;
    private ImageView img_follow_question;
    private TextView text_follow_question;
    private TextView text_answer_num;
    private RecyclerView recyclerView_answer;
    private List<AnswerItemView> answerList = new ArrayList<>();
    private int qid;
    private boolean isPause = false;
    private int hasFollow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail);
        Intent intent = getIntent();
        qid = intent.getIntExtra("qid", -1);

        question_back = findViewById(R.id.question_back);
        detail_to_search = findViewById(R.id.detail_to_search);
        text_question_title = findViewById(R.id.text_question_title);
        text_question_content = findViewById(R.id.text_question_content);
        text_author = findViewById(R.id.text_author);
        img_invite_to_answer = findViewById(R.id.img_invite_to_answer);
        img_go_write_answer = findViewById(R.id.img_go_write_answer);
        img_follow_question = findViewById(R.id.img_follow_question);
        text_follow_question = findViewById(R.id.text_follow_question);
        text_answer_num = findViewById(R.id.text_answer_num);

        recyclerView_answer = findViewById(R.id.recyclerView_answer);
        LinearLayoutManager layoutManager;
        layoutManager = new LinearLayoutManager(this);
        recyclerView_answer.setLayoutManager(layoutManager);//建立线性布局
        QuestionDetailAdapter adapter = new QuestionDetailAdapter(answerList);//创建适配器
        recyclerView_answer.setAdapter(adapter);//将视图与适配器连接起来

        getQuestionDetail();

        //各种组件的动作设置
        //返回键
        question_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //搜索键
        detail_to_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 跳转到搜索页面
            }
        });
        //邀请回答
        img_invite_to_answer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 邀请回答功能待完善，目前不实现
            }
        });
        //写回答
        img_go_write_answer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QuestionDetailActivity.this, AnswerActivity.class);
                intent.putExtra("qid",qid);
                intent.putExtra("qtitle",text_question_title.getText().toString());
                startActivity(intent);
            }
        });
        //关注问题
        img_follow_question.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(hasFollow==0){
                    followQuestion();
                }else{
                    cancelFollowQuestion();
                }
            }
        });


    }

    private void cancelFollowQuestion() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = LoginActivity.SERVER_URL+"/main-servlet?action=cancelFollowQuestion&qid="+qid+"&iduser="+BaseActivity.owner.getNetId();
                    OkHttpUtil.asyGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            runOnUiThread(new Runnable(){
                                @Override
                                public void run() {
                                    if(jsonStr.equals("success")){
                                        img_follow_question.setImageResource(R.mipmap.follow_question);
                                        text_follow_question.setText("关注问题");
                                        hasFollow=0;
                                    }else{
                                        Toast.makeText(getApplicationContext(), jsonStr,Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void followQuestion() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = LoginActivity.SERVER_URL+"/main-servlet?action=followQuestion&qid="+qid+"&iduser="+BaseActivity.owner.getNetId();
                    OkHttpUtil.asyGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            runOnUiThread(new Runnable(){
                                @Override
                                public void run() {
                                    if(jsonStr.equals("success")){
                                        img_follow_question.setImageResource(R.mipmap.has_follow);
                                        text_follow_question.setText("已关注");
                                        hasFollow=1;
                                    }else{
                                        Toast.makeText(getApplicationContext(), jsonStr,Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getQuestionDetail() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = LoginActivity.SERVER_URL+"/main-servlet?action=getQuestionDetail&qid="+qid+"&iduser="+BaseActivity.owner.getNetId();
                    OkHttpUtil.asyGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            Gson gson = new Gson();
                            Map<String, String> jsonMap = gson.fromJson(jsonStr, new TypeToken<Map<String, String>>() {}.getType());
                            answerList = gson.fromJson(jsonMap.get("answerList"), new TypeToken<List<AnswerItemView>>() {}.getType());
                            runOnUiThread(new Runnable(){
                                @Override
                                public void run() {
                                    text_question_title.setText(jsonMap.get("qtitle"));
                                    text_question_content.setText(jsonMap.get("qcontent"));
                                    text_author.setText(jsonMap.get("username"));
                                    String num = "（"+ answerList.size() +")";
                                    text_answer_num.setText(num);
                                    QuestionDetailAdapter adapter = new QuestionDetailAdapter(answerList);//创建适配器
                                    recyclerView_answer.setAdapter(adapter);//将视图与适配器连接起来
                                    hasFollow = Integer.parseInt(jsonMap.get("hasFollow"));
                                    if(hasFollow==1){
                                        img_follow_question.setImageResource(R.mipmap.has_follow);
                                        text_follow_question.setText("已关注");
                                    }
                                }
                            });
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPause = true; //记录页面已经被暂停
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPause){ //判断是否暂停
            isPause = false;
            getQuestionDetail();
            QuestionDetailAdapter adapter = new QuestionDetailAdapter(answerList);//创建适配器
            recyclerView_answer.setAdapter(adapter);//将视图与适配器连接起来
        }

    }
}