using Microsoft.AspNetCore.Mvc;
using OI.Metrology.Shared.DataModels;
using OI.Metrology.Shared.Repositories;
using OI.Metrology.Shared.Services;
using System;
using System.IO;

namespace OI.Metrology.Viewer.ApiControllers;
public class AttachmentsController : Controller
{
    private readonly IMetrologyRepo _Repo;
    private readonly IAttachmentsService _AttachmentsService;

    public AttachmentsController(IMetrologyRepo repo, IAttachmentsService attachmentsService)
    {
        _Repo = repo;
        _AttachmentsService = attachmentsService;
    }

    // this endpoint was created in hope that it would make retrieving attachments to display in OpenInsight easier
    // url would be like /api/attachments/mercuryprobe/header/HgProbe_66-232268-4329_20180620052640032/data.pdf

    [HttpGet("/api/attachments/{toolTypeName}/{tabletype}/{title}/{filename}")]
    public IActionResult GetAttachment(
        string toolTypeName,
        string tabletype,
        string title,
        string filename)
    {
        ToolType tt = _Repo.GetToolTypeByName(toolTypeName);

        bool header = !string.Equals(tabletype.Trim(), "data", StringComparison.OrdinalIgnoreCase);

        try
        {
            string contenttype = "application/pdf";
            if (filename.ToLower().TrimEnd().EndsWith(".txt"))
                contenttype = "text/plain";

            Stream fs = _AttachmentsService.GetAttachmentStreamByTitle(tt, header, title, filename);
            return File(fs, contenttype);
        }
        catch (Exception ex)
        {
            return Content(ex.Message);
        }

    }

}