@inherits FnzComponentBase

@code {
    private FnzBootstrapModal mdl;
    private Guid PlaylistId { get; set; }

    private string ExportName { get; set; } = "brrr";
    private bool ExportDomainCheck { get; set; } = true;
    private string ExportDomain { get; set; } = "brrr";
    private bool ExportDateCheck { get; set; } = true;
    private string ExportDate { get; set; } = "brrr";
    private string ExportExtension { get; set; } = "brrr";
    private int ExportCodePage { get; set; } = 0;
    private string ExportMime { get; set; } = "brrrr";

    private string _exportDataUri = null;
    private string _exportFileName = null;
}

@code{


    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

}

<FnzBootstrapModal @ref="mdl">
    <Title>Export playlist</Title>
    <Body>
        <div class="input-group mb-3">
            <span class="input-group-text">File Name</span>
            <InputText class="form-control" placeholder="Filename"
                       Value="@ExportName"
                       ValueExpression="()=>ExportName"
                       ValueChanged="s=>ExportName=s"></InputText>
        </div>
        <div class="input-group mb-3">
            <div class="input-group-text">
                <label>
                    <input class="form-check-input mt-0 align-middle" type="checkbox" checked="@ExportDomainCheck" @bind-value="ExportDomainCheck">
                    <span class="align-middle">-Host</span>
                </label>
            </div>
            <InputText class="form-control"
                       Value="@ExportDomain"
                       ValueExpression="()=>ExportDomain"
                       ValueChanged="s=>ExportDomain=s"></InputText>
        </div>
        <div class="input-group mb-3">
            <div class="input-group-text">
                <label>
                    <input class="form-check-input mt-0 align-middle" type="checkbox" checked="@ExportDateCheck" @bind-value="ExportDateCheck">
                    <span class="align-middle">-Date</span>
                </label>
            </div>
            <InputText class="form-control"
                       Value="@ExportDate"
                       ValueExpression="()=>ExportDate"
                       ValueChanged="s=>ExportDate=s"></InputText>
        </div>
        <div class="input-group mb-3">
            <span class="input-group-text">Text Encoding</span>
            <InputSelect class="form-control" TValue="int"
                         Value="ExportCodePage"
                         ValueExpression="() => ExportCodePage"
                         ValueChanged="i=>EncodingChanged(i)">
                @foreach (var en in Encoding.GetEncodings()
                .OrderBy(p => p.Name != "utf-8")
                .ThenBy(p => p.Name != "gb2312")
                .ThenBy(p => p.Name != "shift_jis")
                .ThenBy(p => p.Name))
                {
                    <option value="@en.CodePage">@en.Name (@en.CodePage)</option>
                }
            </InputSelect>
        </div>
        <div class="input-group mb-3">
            <span class="input-group-text">Extension</span>
            <InputText type="text" class="form-control" placeholder="Extension"
                       Value="@ExportExtension"
                       ValueExpression="()=>ExportExtension"
                       ValueChanged="s=>ExportExtension=s"></InputText>
        </div>
        <div class="input-group mb-3">
            <span class="input-group-text">Mime</span>
            <InputText type="text" class="form-control" placeholder="Extension" ValueExpression="()=>ExportMime" Value="@ExportMime"></InputText>
        </div>
    </Body>
    <Footer>
        <div class="input-group">
            <button class="btn btn-primary" @onclick="DoExport">
                <i class="bi bi-save"></i>
                Save
            </button>

            <button class="btn btn-primary" @onclick="@DoExportAsDataUri">
                <i class="bi bi-gear"></i>
                Generate Data URI
            </button>

            @if (_exportDataUri != null)
            {
                <span class="btn btn-success">
                    <i class="bi bi-link"></i>
                    <a href="@_exportDataUri" download="@_exportFileName">Data URI</a>
                </span>
            }
        </div>

    </Footer>
</FnzBootstrapModal>

@code {
    public void Show(Guid playlistId)
    {
        var playlist = PlaylistHelper.PlayListLoadSave[playlistId];
        var uri = new Uri(NavigationManager.Uri);
        ExportName = $"{playlist}";
        ExportDomain = uri.Host;
        ExportDate = $"{DateTime.Now:yyMMdd}";
        ExportCodePage = 65001;
        ExportExtension = "m3u8";
        ExportMime = "application/mpegurl";

        PlaylistId = playlistId;
        _exportDataUri = null;
        StateHasChanged();
        mdl.Show();
    }

    private void EncodingChanged(int value)
    {
        ExportCodePage = value;
        ExportExtension =
            ExportCodePage == 65001
                ? "m3u8"
                : "m3u";
        StateHasChanged();
    }

    public void DoExport()
    {
        var fileName = GenerateExportFileName();
        var content = GenerateM3U( );

        JSRuntime.InvokeVoidAsync("fnz.downloadFile", fileName, ExportMime, content);
        mdl.Hide();
    }

    private void DoExportAsDataUri()
    {
        var outBuf = GenerateM3U( );
        _exportFileName = GenerateExportFileName();
        _exportDataUri = $"data:{ExportMime};base64," + Convert.ToBase64String(outBuf, Base64FormattingOptions.None);
    }

    private string GenerateExportFileName()
    {
        var sbFn = new StringBuilder(ExportName);

        if (ExportDomainCheck) sbFn.Append($"-{ExportDomain}");
        if (ExportDateCheck) sbFn.Append($"-{ExportDate}");

        sbFn.Append($".{ExportExtension}");
        return sbFn.ToString();
    }

    private byte[] GenerateM3U( )
    {
        var encoding = Encoding.GetEncoding(ExportCodePage);

        // generate m3u content
        var sbM3 = new StringBuilder();
        sbM3.WriteM3U8Header(encoding);

        foreach (var item in PlaylistHelper[PlaylistId])
        {
            var track = DataSet.AllTracks.FirstOrDefault(p => p.Path == item);
            if (track == null) continue;

            sbM3.AppendLine($"#EXTINF:{track.Tag?.Duration ?? 0} logo=\"{track.Disc.CoverPath.UrlEscape()}\",{track.Tag?.Artist} - {track.Tag?.Title ?? track.Name}");
            sbM3.AppendLine(track.Path.UrlEscape());
        }

        var outBuf = encoding.GetBytes(sbM3.ToString());


        return outBuf;
    }



}
