<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="Dangrain_Y.ico" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bitter</title>
</head>
<body>
    <div>
        <h2>Post a Bitter yourself!</h2>
        <textarea id="tweetInput" rows="4" cols="50"></textarea>
        <br>
        <button onclick="postTweet()">Post</button>
    </div>

    <div>
        <h2>Posted Bitters</h2>
        <ul id="tweetList"></ul>
    </div>

    <script>
        const username = 'Dangrainage';
        const repo = 'Urban';
        const token = 'https://bin.youshitsune.tech/?0917bcd247d5c698#6pMTqBc5Qev8a1ZVepsXMgUGAcVjimnbijfNiQHaonvE';

        // GitHub API endpoint
        const githubApiUrl = `https://api.github.com/repos/${username}/${repo}/contents/`;

        // Fetch tweets from the GitHub repository
        function fetchTweets() {
            fetch(githubApiUrl)
                .then(response => response.json())
                .then(responseData => {
                    // Check if responseData is an array
                    const files = Array.isArray(responseData) ? responseData : [];

                    const tweetFiles = files
                        .filter(file => file.name.endsWith('.json'))
                        .sort().reverse(); // Sort by filename in descending order

                    // Display tweets
                    displayTweets(tweetFiles);
                })
                .catch(error => console.error('Error fetching tweets:', error));
        }

        // Display tweets on the page
        function displayTweets(tweetFiles) {
            const tweetList = document.getElementById('tweetList');
            tweetList.innerHTML = '';

            tweetFiles.forEach(file => {
                const listItem = document.createElement('li');

                // Fetch and display tweet content
                fetch(`${githubApiUrl}${file.name}`)
                    .then(response => response.json())
                    .then(tweet => {
                        const tweetText = JSON.parse(atob(tweet.content)).text;
						var time = new Date(parseInt(file.name.replace('.json', '').replace('tweet_', '')))

                        // Create a paragraph for each tweet
                        const paragraph = document.createElement('p');
                        paragraph.textContent = time.toLocaleDateString("en-GB") + " " + time.toLocaleTimeString("en-GB") + ": " + tweetText;

                        listItem.appendChild(paragraph);
                    })
                    .catch(error => console.error('Error fetching tweet content:', error));

                // Append the tweet to the list
                tweetList.appendChild(listItem);
            });
        }

        // Post a new tweet
        function postTweet() {
            const tweetInput = document.getElementById('tweetInput');
            const tweetText = tweetInput.value;

            if (tweetText.trim() !== '') {
                const timestamp = Date.now();
                const fileName = `tweet_${timestamp}.json`;
                const fileContent = JSON.stringify({ text: tweetText }, null, 2);

                // Create a new tweet file
                createFile(fileName, fileContent);

                // Clear the input field
                tweetInput.value = '';
            }
        }

        // Create a new file in the GitHub repository
        function createFile(fileName, fileContent) {
            const apiUrl = `${githubApiUrl}${fileName}`;
            const data = {
                message: `Add tweet: ${fileName}`,
                content: btoa(fileContent),
                branch: 'main'
            };

            fetch(apiUrl, {
                method: 'PUT',
                headers: {
                    'Authorization': `token ${token}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(() => {
                // Fetch and display the updated tweets
                fetchTweets();
            })
            .catch(error => console.error('Error creating file:', error));
        }
		
		function timeConverter(UNIX_timestamp){
			var a = new Date(UNIX_timestamp * 1000);
			var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
			var year = a.getFullYear();
			var month = months[a.getMonth()];
			var date = a.getDate();
			var hour = a.getHours();
			var min = a.getMinutes();
			var sec = a.getSeconds();
			var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
			return time;
		}

        // Fetch and display tweets when the page loads
        fetchTweets();
    </script>
</body>
</html>