//
//  AttachmentPreviewViewController.swift
//  Tusker
//
//  Created by Shadowfacts on 3/20/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm
import TuskerComponents

class AttachmentPreviewViewController: UIViewController {

    private let attachment: Attachment
    private let sourceView: AttachmentView
    
    init(sourceView: AttachmentView) {
        self.attachment = sourceView.attachment
        self.sourceView = sourceView

        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        if let data = ImageCache.attachments.getData(attachment.url),
            let image = UIImage(data: data) {
            let imageView: UIImageView
            if attachment.url.pathExtension == "gif" {
                let gifView = GIFImageView(image: image)
                let controller = sourceView.gifController ?? GIFController(gifData: data)
                controller.attach(to: gifView)
                controller.startAnimating()
                imageView = gifView
            } else {
                imageView = UIImageView(image: image)
            }
            imageView.contentMode = .scaleAspectFit
            imageView.backgroundColor = .black
            view = imageView
            preferredContentSize = image.size
        } else {
            view = UIActivityIndicatorView(style: .large)
        }
    }
}
