//  AttachmentViewController.swift
//  Tusker
//
//  Created by Shadowfacts on 6/14/19.
//  Copyright © 2019 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

class PendingLargeImageViewController: UIViewController {
    
    let url: URL
    let cache: ImageCache
    let imageDescription: String?

    var largeImageVC: LargeImageViewController?
    var loadingVC: LoadingViewController?
    
    var imageRequest: ImageCache.Request?
    
    private var initialControlsVisible: Bool = true
    var controlsVisible: Bool {
        get {
            return largeImageVC?.controlsVisible ?? initialControlsVisible
        }
        set {
            if let largeImageVC = largeImageVC {
                largeImageVC.setControlsVisible(newValue, animated: false)
            } else {
                initialControlsVisible = newValue
            }
        }
    }
    
    override var childForHomeIndicatorAutoHidden: UIViewController? {
        return largeImageVC
    }
    
    init(url: URL, cache: ImageCache, imageDescription: String?) {
        self.url = url
        self.cache = cache
        self.imageDescription = imageDescription
        
        super.init(nibName: nil, bundle: nil)
    }
    
    convenience init(attachment: Attachment) {
        self.init(url: attachment.url, cache: .attachments, imageDescription: attachment.description)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        overrideUserInterfaceStyle = .dark
        view.backgroundColor = .black
        
        if let data = cache.get(url) {
            createLargeImage(data: data)
        } else {
            loadingVC = LoadingViewController()
            embedChild(loadingVC!)
            imageRequest = cache.get(url) { [weak self] (data) in
                guard let self = self else { return }
                self.imageRequest = nil
                DispatchQueue.main.async {
                    self.loadingVC?.removeViewAndController()
                    self.createLargeImage(data: data!)
                }
            }
        }
    }
    
    override func didMove(toParent parent: UIViewController?) {
        super.didMove(toParent: parent)
        
        if parent == nil {
            imageRequest?.cancel()
        }
    }
    
    func createLargeImage(data: Data) {
        guard let image = UIImage(data: data) else { return }
        largeImageVC = LargeImageViewController(image: image, description: imageDescription, sourceInfo: nil)
        largeImageVC!.initialControlsVisible = initialControlsVisible
        largeImageVC!.shrinkGestureEnabled = false
        if url.pathExtension == "gif" {
            largeImageVC!.gifData = data
        }
        embedChild(largeImageVC!)
    }
    
}
