import { useNavigate, useParams } from 'react-router-dom';
import React, { useEffect, useState, useContext} from 'react';
import Article from '../components/Article.js';
import { UserContext, ArticleContext } from '../Context.js';
import MapLocator from '../components/MapForLoaction.js';
import Comment from '../components/Comment.js';

import axios from 'axios';
axios.defaults.withCredentials = true;

function PostRead() {
  let params = useParams();
  const userContext = useContext(UserContext);
  const articleContext = useContext(ArticleContext);

  const [article, setArticle] = useState(null)
  const [inputComment, setInputComment] = useState("")
  const [commentList, setCommentList] = useState("")
  const navigate = useNavigate();
  function MoveTo(link){
    navigate(link)
  }	
  useEffect(() => {
    userContext.CheckSession()
    .then((response) => {
      if (!response.data) {
        alert("세션이 만료되었습니다. 다시 로그인 바랍니다.")
        MoveTo('/login')
      } 
      else{
        return requestLoadArticleById(params.id)
      }
    })
    .then((response) => {
      console.log(response)
      setArticle(response.data)
      
    })
    .catch((response)=>{
      console.log("error!:LogOut")
      console.log(response)
    })

  }, []);  

  function SetLike(){
    axios.put(`http://localhost:8080/article/${params.id}/comment/like`)
    .then(res => {
      alert("The comment is successfully uploaded");
      return requestLoadArticleById(params.id)
    })
    .then(res => {
      setArticle(res.data)
    })
    .catch(err => {
      console.error(err);
    });
  }

  const onTextChange = (e) => {
    const {value} = e.target;
    setInputComment(value);
  }

  const onSubmit = e => {
    e.preventDefault();
    if (!inputComment) {
      alert("댓글을 작성해주세요.");
      return
    }
    const data = {content: inputComment}
    axios.post(`http://localhost:8080/article/${params.id}/comment`, data,
    {
      headers: {"Content-Type": 'application/json'}
    })
    .then(res => {
      alert("The comment is successfully uploaded");
      return requestLoadArticleById(params.id)
    })
    .then(res => {
      setArticle(res.data)
    })
    .catch(err => {
      console.error(err);
    });
  };

  if (article) {
    return(
      <>
        <div className="introduction" style={{display: 'flex'}}>
          <MapLocator loc={{lat: article.latitude, lng: article.longitude}} keyword={article.keyword}></MapLocator>
          <div>
            <Article data={article}></Article>
            <button onClick={SetLike}>조와요</button>
          </div>
        </div>
        <form onSubmit={onSubmit}>
          <div style={{display: 'flex'}}>
            <button>댓글 작성</button>
            <input type="text" onChange={onTextChange}></input>
          </div>
        </form>   
        <ArticleContext.Provider value={{requestLoadArticleById, setArticle}}>
          {
            article.comments.map((el)=>{
              return(
                <Comment key={el._id} data={el}></Comment>
              )
            })
          }
        </ArticleContext.Provider>
      </>
    )    
  }
  else {
    return(
      <div className="introduction" style={{display: 'flex'}}>
        <p>로딩준</p>
      </div>
    )
  }
}

async function requestLoadArticleById(id) {
  const response = await axios({
    url: `http://localhost:8080/article/${id}`, // 통신할 웹문서
    method: 'get', // 통신할 방식
  });
  return response;
}

export default PostRead;