#include <cstdio>
#include "config.hh"
#include "ctcset.hh"

using namespace std;

#include "base62.hh"
#include "wstring.hh"
#include "scriptfile.hh"

static FILE *scriptout;

void OpenScriptFile(const string& filename)
{
    scriptout = fopen(filename.c_str(), "wt");
    if(!scriptout)
    {
        perror(filename.c_str());
    }
}

void CloseScriptFile()
{
    fclose(scriptout);
}

void PutAscii(const std::u32string& comment)
{
    static wstringOut conv;
    conv.SetSet(getcharset());
    fprintf(scriptout, "%s", conv.puts(comment).c_str());
}

static std::u32string CurLabel = U"";
static std::u32string CurLabelComment = U"";

void BlockComment(const std::u32string& comment)
{
    CurLabelComment = comment;
}
void StartBlock(const std::u32string& blocktype,
                const std::u32string& reason,
                unsigned intparam)
{
    StartBlock(wformat(blocktype.c_str(), intparam), reason);
}
void StartBlock(const std::u32string& blocktype, const std::u32string& reason)
{
    bool newlabel = true;//CurLabel != Buf;
    bool comment = !CurLabelComment.empty();

    if(newlabel)
    {
        if(!CurLabel.empty()) PutAscii(U"\n\n");
    }

    if(newlabel)
    {
        // FIXME: iconv here
        if(!blocktype.empty())
        {
            std::u32string blockheader = U"*";
            blockheader += blocktype;
            blockheader += U';';
            blockheader += reason;
            blockheader += U'\n';
            PutAscii(blockheader);
        }
        CurLabel = blocktype;
    }
    if(comment)
    {
        PutAscii(U";-----------------\n");
        PutAscii(CurLabelComment);
        PutAscii(U";-----------------\n");
    }
}
void EndBlock()
{
    //PutAscii("\n\n");
    CurLabelComment.clear();
}
const std::u32string Base62Label(const unsigned noffs)
{
    return AscToWstr(EncodeBase62(noffs, 4));
}
void PutBase62Label(const unsigned noffs)
{
    PutAscii(wformat(U"$%ls:", Base62Label(noffs).c_str()));
}
void PutBase16Label(const unsigned noffs)
{
    PutAscii(wformat(U"$%X:", noffs));
}
void PutBase10Label(const unsigned noffs)
{
    PutAscii(wformat(U"$%u:", noffs));
}
void PutContent(const std::u32string& s, bool dolf)
{
    if(dolf) PutAscii(U"\n");
    PutAscii(s);
    PutAscii(U"\n");
}
