import React, { Key } from "react";
import { jwtDecode } from 'jwt-decode';
import Cookies from 'js-cookie';

class Post {
    id: Number;
    authorId: Number;
    type: Number;
    message: String;
    date: Date;
    constructor(id: Number, authorId: Number, type: Number, message: String, date: Date) {
        this.id = id;
        this.authorId = authorId;
        this.type = type;
        this.message = message;
        this.date = date;
    }
}

function PostTag(post: Post) {

    const goToUpdate = () => {
        window.location.href=`../post/?postId=${post.id}`
    }

    const deletePost = async () => {
        await fetch(`/api/v1/post/delete/${post.id}`, {
            method: "DELETE"
        }).then(response => console.log(response));
    }


    const amIAnAuthor = jwtDecode(Cookies.get("jwt")!).id == post.authorId;

    let content;
    if (post.type == 1) {
        if ([".mp4", ".webm"].indexOf(post.message.slice(-4).toLowerCase()) > -1) {
            content = <video>
                <source src={`/media/${post.message}`} />
            </video>
        } else {
            content = <img width="50%" height="50%" src={`/media/${post.message}`} />
        }
    } else {
        content = post.message;
    }
    return (
        <div className="post" key={post.id as Key}>
            {content}
            {amIAnAuthor ? (
                <div>
                    <button onClick={goToUpdate} >изменить</button>
                    <br></br>
                    <button onClick={deletePost}>удалить</button></div>

            ) : (
                <></>
            )}
        </div>
    );
}

export default { Post, PostTag };