//
//  SearchViewModel.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/11.
//

import Alamofire
import Foundation

struct RelateMode: Codable {
    var keyword: String = ""
    var relateItems: [String] = []
}

class SearchViewModel: NSObject {
    @Published var relateModel: RelateMode?

    var keyword: String = "" {
        didSet {
            requestAssociateRelate()
        }
    }

    var task: URLSessionTask?

    func requestAssociateRelate() {
        if keyword.isEmpty {
            return
        }

        task?.cancel()

        let param = ["ds": "yt",
                     "hl": "en",
                     "client": "firefox",
                     "q": keyword,
        ]

        task = AF.request("http://suggestqueries.google.com/complete/search", method: .get, parameters: param, encoding: URLEncoding.default).responseData { response in
            switch response.result {
            case let .success(data):
                var model = RelateMode()
                if let objc: [Any] = data.toJSON() as? [Any] {
                    if let keyword = objc.first as? String {
                        model.keyword = keyword
                    }
                    if let relates = objc[1] as? [String] {
                        model.relateItems = relates
                    }
                }
                self.relateModel = model
                break
            case let .failure(failure):
                break
            }
        }.task
    }
}

extension SearchViewModel: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return relateModel?.relateItems.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "RelateSeachCell", for: indexPath) as? RelateSeachCell {
            if let model = relateModel {
                if indexPath.row < model.relateItems.count {
                    let keyword = model.relateItems[indexPath.row]
                    cell.keywordLabel.text = keyword
                }
            }
            return cell
        }
        return RelateSeachCell()
    }
}

extension Data {
    func toJSON() -> AnyObject? {
        do {
            return try JSONSerialization.jsonObject(with: self, options: .mutableContainers) as AnyObject
        } catch {
            print(error)
        }
        return nil
    }
}
