using Microsoft.AspNetCore.Mvc;
using OI.Metrology.Shared.DataModels;
using OI.Metrology.Shared.Models.Stateless;
using OI.Metrology.Shared.Services;

namespace OI.Metrology.Server.ApiControllers;

public class AttachmentsController : Controller
{

    private readonly IAttachmentsService _AttachmentsService;
    private readonly IMetrologyRepository _MetrologyRepository;

    public AttachmentsController(IMetrologyRepository metrologyRepository, IAttachmentsService attachmentsService)
    {
        _AttachmentsService = attachmentsService;
        _MetrologyRepository = metrologyRepository;
    }

    // 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 = _MetrologyRepository.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); }
    }

}