//
//  HistoryViewModel.swift


import Foundation
import UIKit
import SDWebImage
import Kingfisher

class HistoryViewModel : NSObject{
    
    let arrHistroyList : BoxBind<[HistoryListModel]> = BoxBind([HistoryListModel]())
    var have_more_pages : BoxBind<Bool> = BoxBind(Bool())
    
    override init() {
        super.init()
        self.callHistoryListAPI(current_page: 1, page_limit: 10, isFromResend: false, completion: nil)
    }
    
    func callHistoryListAPI(current_page: Int, page_limit : Int,isFromResend : Bool,justRefresh: Bool? = false, completion: ((Bool) -> Void)? = nil){
        APIDataManager.shared.getHistoryList(current_page: current_page, page_limit: page_limit) { historyData in
            if historyData.widget_history.count != 0{
                self.have_more_pages.value = historyData.have_more_pages ?? false
                if isFromResend{
                    if let latestData = historyData.widget_history.first{
                        self.arrHistroyList.value.insert(latestData, at: 0)
                    }
                }
                else{
                    for data in historyData.widget_history{
                        if isFromResend{
                            self.arrHistroyList.value.insert(data, at: 0)
                        }
                        else{
                            if self.arrHistroyList.value.contains(where: {$0.created_at == data.created_at}){}else{
                                (justRefresh ?? false) ? self.arrHistroyList.value.insert(data, at: 0) : self.arrHistroyList.value.append(data)
                                //because when recevied notification if I remove above code then latest record display last but we need to display it in first position
                                
                            }
                        }
                    }
                }
                completion?(true)
            }
        }
    }
    
    func showDeleteAlert(index : Int){
        let actionSheet = UIAlertController(title: Alert_Message.deleteTitle, message: Alert_Message.deleteHistoryMsg, preferredStyle: .alert)

        let removeAction = UIAlertAction(title: Alert_Message.Delete, style: .destructive) { (action) in
            if Reachability.isInternetAvailable{
                APIDataManager.shared.deleteImageHistory(imageId: String(self.arrHistroyList.value[index].id ?? 0)) { success,message in
                    if success{
                        if let index = self.arrHistroyList.value.firstIndex(where: { $0.id == self.arrHistroyList.value[index].id }){
                            self.arrHistroyList.value.remove(at: index)
                        }
                    }
                    else{
                        Utilities.showAlertView(nil, message) { _ in}
                    }
                }
            }
            else{
                Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { _ in}
            }
        }

        let cancelAction = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) in
            debugPrint("didPress cancel")
        }
        
        actionSheet.addAction(cancelAction)
        actionSheet.addAction(removeAction)

        if let currentVC = UIApplication.shared.topViewController() as? HistoryViewController {
            currentVC.present(actionSheet, animated: true, completion: nil)
        }
    }
    
    @objc func showActionSheet(_ sender: UITapGestureRecognizer){
        if let sender = sender as? CustomTapGesture {
            let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            let resendAction = UIAlertAction(title: Alert_Message.Resend, style: .default) { (action) in
                
                ScreenManager.shared.moveToPickFriendVC(capturedImage: nil, isFromHistory: true, imageId: self.arrHistroyList.value[sender.index].id ?? 0) { isPhotoSent in
                    self.callHistoryListAPI(current_page: 0, page_limit: 10, isFromResend: true)
                }
            }
            
            let shareAction = UIAlertAction(title: Alert_Message.Share, style: .default) { (action) in
                if let currentVC = UIApplication.shared.topViewController() as? HistoryViewController {
                    let vc = UIActivityViewController(activityItems: [sender.historyCell.historyImgView.image!] , applicationActivities: [])
                    if DeviceType.ISPAD{
                            if vc.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
                                vc.popoverPresentationController?.sourceView = sender.historyCell.optionBtn
                            }
                        }//
                        currentVC.present(vc, animated: true)
                }
            }
            
            let deleteAction = UIAlertAction(title: Alert_Message.Delete, style: .destructive) { (action) in
                self.showDeleteAlert(index: sender.index)
            }
            
            let cancelAction = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) in
                debugPrint("didPress cancel")
            }
            
            actionSheet.addAction(resendAction)
            actionSheet.addAction(shareAction)
            actionSheet.addAction(deleteAction)
            actionSheet.addAction(cancelAction)
            
            if let currentVC = UIApplication.shared.topViewController() as? HistoryViewController {
                actionSheet.popoverPresentationController?.sourceView = sender.historyCell.optionBtn
                actionSheet.popoverPresentationController?.permittedArrowDirections = .up
                currentVC.present(actionSheet, animated: true, completion: nil)
            }
        }
    }
    
    func getHistoryTimeline(createdTime : Int) -> String{
        
        let dateTimestamp = Date(timeIntervalSince1970: TimeInterval(createdTime))
        let currentDate = Utilities.getExpectedDateFormat(date: Date(), dateFormat: "dd MMMM")
        let timestampDate = Utilities.getExpectedDateFormat(date: dateTimestamp, dateFormat: "dd MMMM")
        
        let currentHour = Calendar.current.component(.hour, from: Date())
        let histroyHour = Calendar.current.component(.hour, from: dateTimestamp)
        
        let currentMin = Calendar.current.component(.minute, from: Date())
        let histroyMin = Calendar.current.component(.minute, from: dateTimestamp)
        
        let totalHrs = currentHour - histroyHour
        let totalMin = currentMin - histroyMin
        
        if totalHrs == 0 && totalMin == 0 && timestampDate == currentDate{
            return "Now"
        }
        else if totalHrs == 0 && totalMin != 0 && timestampDate == currentDate{
            return "\(totalMin) m"
        }
        else if totalHrs != 0 && timestampDate == currentDate{
            return "\(totalHrs) h"
        }
        else if timestampDate != currentDate{
            return timestampDate
        }
        else{
            return ""
        }
    }
    
    //MARK: - Delegate and Datasource
    
    func getCellCountForDisplay() -> Int{
        return self.arrHistroyList.value.count
    }
    
    func prepareCellForDisplay(collectionView : UICollectionView, indexPath : IndexPath, historyData : [HistoryListModel])-> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HistoryCollectionViewCell.identifier, for: indexPath) as! HistoryCollectionViewCell
        cell.historyImgView.sd_setImage(with: URL(string: historyData[indexPath.row].image_url ?? ""), placeholderImage: UIImage(named: "image_placeholder"))
        cell.historyImgView.contentMode = .scaleAspectFill
        cell.historyImgView.cornerRadiuss = 16
        
        cell.lblHistoryDetails.text = "\(historyData[indexPath.row].full_name ?? "")"
        cell.lblHours.text = "· \(getHistoryTimeline(createdTime: historyData[indexPath.row].created_at ?? 0))"
        cell.optionBtn.tag = indexPath.row
        cell.optionBtn.layer.cornerRadius = cell.optionBtnHeight.constant / 2
        
        let actionSheetGesture = CustomTapGesture(target: self, action: #selector(showActionSheet(_:)))
        actionSheetGesture.index = indexPath.row
        actionSheetGesture.imageURL =  historyData[indexPath.row].image_url ?? ""
        actionSheetGesture.historyCell = cell
        cell.optionBtn.addGestureRecognizer(actionSheetGesture)
        return cell
    }
}

fileprivate class CustomTapGesture: UITapGestureRecognizer {
    var index = 0
    var imageURL = ""
    var historyCell = HistoryCollectionViewCell()
}
