<div id="article">
    <div class="banner">
        <input type="text" name="title" id="title">
    </div>
    <div class="form">
        <a href="./" id="editlink">View article</a>
        <label for="intro">Introduction</label>
        <textarea name="intro" id="intro"></textarea>
        <label for="content">Content</label>
        <textarea type="textarea" name="content" id="content"></textarea>
        <button id="edit">Update</button>
    </div>
    <div id="message"></div>
    <button id="articleDelete">Delete Article</button>
</div>
<script>
    <% if (locals.auth) { %>
        getArticle()
    <% } else { %>
        window.location = "/article/<%= locals.params.id %>";
    <% } %>
    async function getArticle() {
        // Create a new article and redirect to it
        let resp = await axios({
            url: '/api/article/get',
            method: 'post',
            data: {
                id: "<%= locals.params.id %>"
            }
        });
        resp = await resp.data;
        
        // Failed?
        if (resp.error) return document.querySelector('#message').appendChild(addMessage(resp.error));

        // Are we not the author?
        if (resp.author !== "<%= locals.auth._id %>") return window.location = "/article/<%= locals.params.id %>";

        // Apply information
        document.querySelector('#title').value = resp.title;
        document.querySelector('#intro').innerText = resp.intro;
        document.querySelector('#content').innerText = resp.content;

        // Enable delete button
        document.querySelector('#articleDelete').addEventListener('click', async (e)=>{
        e.preventDefault();
        let test = await axios({
            url: '/api/article/delete',
            method: 'post',
            data: {
                id: resp.id
            }
        })

        console.log(test);

        console.log("Hola");

        //window.location = '/';
    })
    }

    function addMessage(msg) {
        const message = document.createElement('p');
        message.innerText = msg;
        setTimeout(()=>{
            message.remove();
        }, 1000*10)
        return message;
    }

    // Update article on button event
    document.querySelector('#edit').addEventListener('click', async (e)=>{
        e.preventDefault();

        await axios({
            url: '/api/article/edit',
            method: 'post'
        });
    });
</script>