const std = @import("std");
const temp = @import("temp");

const Dimensions = @import("../../Dimensions.zig");
const renderer = @import("../../renderer.zig");

pub const api = @import("../../api/root.zig");

const template = @import("template/root.zig");

const Self = @This();

allocator: std.mem.Allocator,
dimensions: Dimensions,

pub fn init(allocator: std.mem.Allocator, dimensions: Dimensions) Self {
    return .{
        .allocator = allocator,
        .dimensions = dimensions,
    };
}

pub fn render(self: *const Self, response: *const api.spotify.models.GetPlaybackStateResponse) ![]const u8 {
    var arena = std.heap.ArenaAllocator.init(self.allocator);
    defer arena.deinit();

    var context = template.Context{ .title = null };
    if (response.item) |item| {
        switch (item.value) {
            .track => |track| {
                const artists = try arena.allocator().alloc([]const u8, track.artists.len);
                for (track.artists, 0..) |artist, i| {
                    artists[i] = artist.name;
                }

                context.title = .{
                    .title_name = track.name,
                    .artists = artists,
                    .album_name = if (track.album.album_type != .single) track.album.name else null,
                    .album_cover_url = track.album.images[0].url,
                };
            },
            .episode => {},
        }
    }

    const escaped_context = try context.escape(arena.allocator());

    var tmp_file = try temp.TempFile.create(arena.allocator(), .{
        .pattern = "render-spotify-*.html",
    });
    defer tmp_file.deinit();
    const path = try tmp_file.parent_dir.realpathAlloc(arena.allocator(), tmp_file.basename);
    {
        const file = try tmp_file.open(.{ .mode = .write_only });
        defer file.close();
        const writer = file.writer();
        try template.render(
            self.dimensions,
            &escaped_context.value,
            writer.any(),
        );
    }

    return try renderer.render(self.allocator, path, self.dimensions);
}
