//
//  WebViewVC.swift
//  WOKA
//
//  Created by Bilal on 07/06/2024.
//

import UIKit
import WebKit

class WebViewVC: UIViewController, WKNavigationDelegate{

    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var textView: UITextView!
    var url : String?
    var textContent : LinkTypeEnum?
    var pageTitle = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let color1 = #colorLiteral(red: 0.05490196078, green: 0.01176470588, blue: 0.3882352941, alpha: 1)
        let color2 = #colorLiteral(red: 0.2802381199, green: 0.2150136895, blue: 0.8105520973, alpha: 1)
        self.view.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.5))

        self.webView.navigationDelegate = self
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        self.title = pageTitle.capitalized
        if let url {
            Utilities.startProgressHUD()

            webView.isHidden = false
            let link = URL(string:url)!
            let request = URLRequest(url: link)
            webView.load(request)
            Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
                Utilities.dismissProgressHUD()
            }
        }
        
        if let textContent, textContent == .disclaimer{
            if let rtfPath = Bundle.main.url(forResource: "Disclaimer", withExtension: "rtf") {
                do {
                    let rtfData = try Data(contentsOf: rtfPath)
                    let attributedString = try NSAttributedString(data: rtfData, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
                    textView.text = attributedString.string
                    textView.font = FontCustom.shareInstance.customFont(fontName: .Exo2_Medium, size: 17)
                    textView.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
                    textView.textColor = .white
                    self.textView.isHidden = false
                } catch {
                    print("Error loading RTF file: \(error)")
                }
            }
            
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
        self.navigationController?.setColor(color: .white)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
        self.navigationController?.setColor(color: .black)
        
        if self.isMovingFromParent {
            // Back button was pressed
            PersistentStorage.shared.addOthersCount()
        }
    }
}
