import { v4 as uuidv4 } from 'uuid';
import fs from 'node:fs';
import path from 'node:path';
import express from 'express';

import * as Post from './api/post.cjs';
import * as Auth from './api/auth.cjs';
import * as Fetch from './api/fetch.cjs';

const __dirname = path.resolve();
const credentials_file_path = path.join(__dirname, '/config/credentials.json');

if(!fs.existsSync(credentials_file_path)) {
    fs.writeFileSync(
        credentials_file_path,
        JSON.stringify({
            "token": ""
        })
    );   
}

const config = JSON.parse(fs.readFileSync(path.join(__dirname, '/config/config.json')));
const credentials = JSON.parse(fs.readFileSync(credentials_file_path));

let app = express();
let port = process.env.PORT || 4000;
process.env.TZ = config.timezone;

let host = config.host;

let app_name = config.app.name;
let app_callback = config.app.callback;
let app_permission = config.app.permission;

let session_id = uuidv4();
let auth_url = `${host}/miauth/${session_id}?name=${app_name}&callback=${app_callback}&permission=${app_permission}`;

app.get('/callback', function(req, res) {
    if(req.query.session) {
        res.send({
            "status": 200,
            "success": true,
        })
    
        Auth.verify_auth_status();
    } else {
        res.send({
            "status": 400,
            "success": false,
            "message": "Invalid callback request"
        })
    }
    
});

(async () => {
    let access_token = null;

    if(!credentials.token) { // if existing token not exist
        console.log(auth_url);
        await Auth.check_auth_status();
        access_token = await Auth.get_access_token(host, session_id);
        
        let json_data = {
            "token": access_token
        }
        
        fs.writeFileSync(
            credentials_file_path,
            JSON.stringify(json_data)
        );
    } else {
        access_token = credentials.token;
    }

    let static_image_url = "https://weather.bangkok.go.th/Images/Radar/radarh.jpg";
    let animated_image_url = "https://dds.bangkok.go.th/Radar/radar_rain.gif";

    let static_radar_path = path.join(__dirname, '/data/static_radar.jpg');
    let animated_radar_path = path.join(__dirname, '/data/animated_radar.gif');
    await Fetch.get_image_size(static_image_url);

    if(!fs.existsSync(static_radar_path)) {
        await Fetch.save_image(static_image_url, static_radar_path);
    } 

    let post_lap = 0; 
    async function post() {
        let raw_date = new Date();

        let curr_static_image_size = fs.statSync(static_radar_path).size; 
        let fetch_static_image_size = await Fetch.get_image_size(static_image_url);

        console.log("Current size: " + curr_static_image_size);
        console.log("Scanned size: " + fetch_static_image_size);
        
        if(fetch_static_image_size != curr_static_image_size) {
            console.log("File size change detected!");

            await Fetch.save_image(static_image_url, static_radar_path);
            await Fetch.save_image(animated_image_url, animated_radar_path);

            if(post_lap == 0 || post_lap == 36) { // 36 * 5 = 180
                // Fetch static image 
                let static_radar_image_name = `${raw_date.toISOString()}.jpg`;
                const upload_static_radar = await Post.create_image(host, access_token, static_radar_image_name, static_radar_path);
                console.log(upload_static_radar)
                
                // Fetch animated image 
                let animated_radar_image_name = `${raw_date.toISOString()}.gif`;
                const upload_gif_radar = await Post.create_image(host, access_token, animated_radar_image_name, animated_radar_path);
                console.log(upload_gif_radar);

                let radar_caption = await Fetch.get_radar_caption();
                let note_caption = `$[x2 Bangkok Raindar Update]\n**${raw_date.toLocaleString('th-TH')}**\n\n${radar_caption}\n\nLeft: Current Observation\nRight: 3 hour forecast\n\n#bangkok #weather #bangkokweather`
                const post_note = await Post.create_note(
                    host, 
                    access_token, 
                    note_caption,
                    [upload_static_radar.id, upload_gif_radar.id],
                    "public"
                )
                
                if(post_note.createdNote) {
                    console.log("Note created!");

                    if(post_lap == 12) {
                        post_lap = 0;
                    }
                } else {
                    console.log("Note was not created");
                    console.error(post_note);
                }
            }  
            
            post_lap++;
            console.log("Current Lap: %d\n", post_lap);
        } else {
            console.log("No change in data, go on.");
            console.log("Current Lap: %d\n", post_lap);
        } 
    }

    post();
    setInterval(post, 30000);
})();

app.listen(port);
console.log(`Callback URL: http://localhost:${port}/callback`);