import {LayoutProps} from "./Layout.props";
import styles from "./Layout.module.css"
import styles_post from "./Post/Post.module.css"
import {Post} from "./Post/Post";
import cn from "classnames";
import {Component, FunctionComponent} from "react";
import {useContext, useEffect, useState} from "react";
import Cookie from 'js-cookie';
import axios from "axios";
import {Post_int, Blog_int} from "../interfaces/blog_interface"
import blog from "../pages/blog";
import {Button, Form, Input} from "reactstrap";
const Layout = ({ children }: LayoutProps): JSX.Element => {
    const [data, setData] = useState(<></>);
    const [file, setFile] = useState()
    function handleChange(event) {
        setFile(event.target.files[0])
    }
    useEffect(() => {
        //get_posts()
        get_blog()
    }, []);

    function get_blog(){
        if (localStorage.getItem("blog_url") == null){
            axios.get<Blog_int>('http://10.50.20.5:13377/api/blog', {withCredentials: true}).then(response => {
                localStorage.setItem('blog_url', response.data.url);
                get_posts(response.data.url)
            })
        } else{
            get_posts(localStorage.getItem("blog_url"))
        }

    }

    function get_posts(blog_url: string){

        axios.get<Post_int>('http://10.50.20.5:13377/api/blog/'.concat(blog_url), {withCredentials: true}).then(response => {
            let jsonDataPosts = JSON.parse(JSON.stringify(response.data.posts))
            let mydata: JSX.Element
            jsonDataPosts.forEach((post: Post_int) => {
                        mydata = (
                            <>
                                <Post content={post.posts.body} title={post.posts.title}/>
                                {mydata}
                            </>)

                        setData(mydata)

                }
            )
        })
    }
    function sign_out(){
        localStorage.removeItem("blog_url")
        Cookie.remove('sessions')
        window.location.href = "/auth"
    }
    function create_post(){
        axios.post("http://10.50.20.5:13377/api/blog/".concat(localStorage.getItem("blog_url")).concat("/").concat("create_post"), {"title": "test", "body":"test"}, {withCredentials: true}).then( response => {window.location.reload()})
    }

    function blog_list(){
        axios.get("http://10.50.20.5:13377/api/blogs", {withCredentials: true}).then( response => {
            let jsonDataBlogs = JSON.parse(JSON.stringify(response.data))
            let mydata: JSX.Element
            jsonDataBlogs.forEach((post: Blog_int) => {
                    mydata = (
                        <>
                            <pre><code>post.url</code></pre>
                            <pre><code>post.is_private</code></pre>
                            {mydata}
                        </>
                    )

                    setData(mydata)

                }
            )
        })
    }



    function upload_file(){

    }

    function handleSubmit() {
        event.preventDefault()
        const url = 'http://10.50.20.5:13377/file/upload?path=file_storage';
        const formData = new FormData();
        formData.append('file', file);
        const config = {
            withCredentials: true,
            headers: {
                'content-type': 'multipart/form-data',
            },
        };
        axios.post(url, formData, config).then((response) => {
            console.log(response.data);
        });

    }

    function read_post(){
        let num_post = prompt("Input id your post")
        axios.get("http://10.50.20.5:13377/api/blog/".concat(localStorage.getItem("blog_url")).concat("/").concat("post").concat("/").concat(num_post), {withCredentials: true}).then( response => {
            let jsonDataBlogs = JSON.parse(JSON.stringify(response.data))
            let mydata: JSX.Element
            jsonDataBlogs.forEach((post: Blog_int) => {
                    mydata = (
                        <>
                            <pre><code>{mydata}</code></pre>
                        </>
                    )

                    setData(mydata)
                }
            )
        })
    }

    return(
        <div className={styles.container} >
            <div className={styles.utils}>
                <button className={cn(styles.signout, styles.mybtn)} onClick={function (){sign_out()}}>Sign Out</button>
                <button className={cn(styles.create, styles.mybtn)} onClick={function (){create_post()}}>Create Post</button>
                <button className={cn(styles.blog_list, styles.mybtn)} onClick={function (){blog_list()}}>Blogs List</button>
                <button className={cn(styles.read_post, styles.mybtn)} onClick={function (){read_post()}}>Read Post</button>
                <button className={cn(styles.posts_list, styles.mybtn)} onClick={function (){get_posts(localStorage.getItem("blog_url"))}}>Posts List</button>
                <Form onSubmit={handleSubmit}>
                    <h2>Upload</h2>
                    <Input type="file" onChange={handleChange}></Input>
                    <button type="submit">Upload</button>
                </Form>
            </div>
            <h1 className={styles.header}>Test Header</h1>
            <Post className={styles_post.post} content={"test"} title={"test"}/>
            {children}
        </div>
    );
};



export const withLayout = <T extends Record<string, unknown>>(Component: FunctionComponent<T>) => {
    return function withLayoutComponent(props: T): JSX.Element {
        return(
            <Layout>
                <Component {...props} />
            </Layout>
        );
    };
};