import UIKit
import Eureka
import Kingfisher
import SafariServices

class AdsController: FormViewController, MediaBrowserViewControllerDataSource {

    var ads: [VehicleAd] = []
    private var currentAd: VehicleAd?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = NSLocalizedString("Ads", comment: "")
        
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        formatter.timeStyle = .none
        
        for ad in ads {
            let date = Date(timeIntervalSince1970: ad.date)
            let section = Section(formatter.string(from: date))
            
            self.form +++ section
            
            if let price = ad.price {
                section <<< LabelRow() { row in
                    row.title = NSLocalizedString("Price", comment: "")
                    row.value = price
                }
            }

            if let mileage = ad.mileage, mileage != "0" {
                section <<< LabelRow() { row in
                    row.title = NSLocalizedString("Mileage", comment: "")
                    row.value = mileage
                }
            }
            
            if let region = ad.region {
                section <<< LabelRow() { row in
                    row.title = NSLocalizedString("Region", comment: "")
                    row.value = region
                }
            }
            
            if let city = ad.city {
                section <<< LabelRow() { row in
                    row.title = NSLocalizedString("City", comment: "")
                    row.value = city
                }
            }
            
            if let description = ad.adDescription, !description.isEmpty {
                section <<< MultilineLabelRow() { row in
                    row.title = NSLocalizedString("Description", comment: "")
                    row.value = description
                }
            }
            
            if let urlStr = ad.url, let url = URL(string: urlStr) {
                section <<< MultilineLinkRow() { row in
                    row.title = NSLocalizedString("Link", comment: "")
                    row.value = urlStr
                }
                .onCellSelection { _, _ in
                    let safari = SFSafariViewController(url: url)
                    self.present(safari, animated: true)
                }
            }

            if !ad.photos.isEmpty {
                section <<< ImageGridRow() { row in
                    row.value = ad.photos.toArray()
                }
                .onDidSelected { index in
                    self.currentAd = ad
                    let mediaBrowser = MediaBrowserViewController(index: index, dataSource: self, delegate: nil)
                    mediaBrowser.shouldShowTitle = false
                    self.present(mediaBrowser, animated: true, completion: nil)
                }
            }
        }
    }
    
    // MARK: - MediaBrowserViewControllerDataSource
    
    func numberOfItems(in mediaBrowser: MediaBrowserViewController) -> Int {
        guard let images = self.currentAd?.photos else { return 0 }
        return images.count
    }

    func mediaBrowser(_ mediaBrowser: MediaBrowserViewController, imageAt index: Int, completion: @escaping MediaBrowserViewControllerDataSource.CompletionBlock) {
        guard let images = self.currentAd?.photos, let url = URL(string: images[index]) else {
            completion(index, nil, ZoomScale.default, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Image not found"]))
            return
        }
        
        KingfisherManager.shared.retrieveImage(with: url) { result in
            switch result {
            case .success(let res):
                completion(index, res.image, ZoomScale.default, nil)
                break
            case .failure(let error):
                completion(index, nil, ZoomScale.default, error)
                break
            }
        }
    }
}
