//
//  AboutViewController.swift
//  NearbyStores
//
//  Created by DT Team on 7/17/18.
//  Copyright © DT Team. All rights reserved.
//

import UIKit
import Atributika
import AssistantKit
import SwiftUI
import SwiftWebVC

class AboutViewController: MyUIViewController {
    

    
    

    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackview: UIStackView!
    @IBOutlet weak var stackViewRightConstraint: NSLayoutConstraint!
    @IBOutlet weak var stackViewLeftConstraint: NSLayoutConstraint!
    @IBOutlet weak var aboutLabel: UILabel!

    @IBOutlet weak var addressContainer: UIView!
    @IBOutlet weak var addressLabel: UILabel!
    
    @IBOutlet weak var emailContainer: UIView!
    @IBOutlet weak var emailButton: UIButton!
    @IBAction func emailAction(_ sender: Any) {
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_contact_email"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: "mailto:\(config.getValue(defaultValue: ""))") {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
    }
    
    
    
    @IBOutlet weak var phoneContainer: UIView!
    @IBOutlet weak var phoneButton: UIButton!
    @IBAction func phoneAction(_ sender: Any) {
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_contact_phone"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: "tel://\(config.getValue(defaultValue: ""))"), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
    }
    
    
    
    @IBOutlet weak var facebookContainer: UIView!
    @IBOutlet weak var facebookButton: UIButton!
    @IBAction func facebookAction(_ sender: Any) {
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_follow_facebook"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
    }
    
    
    
    @IBOutlet weak var instagramContainer: UIView!
    @IBOutlet weak var instagramButton: UIButton!
    @IBAction func instagramAction(_ sender: Any) {
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_follow_instagram"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
    }
    
    
    @IBOutlet weak var twitterContainer: UIView!
    @IBOutlet weak var twitterButton: UIButton!
    @IBAction func twitterAction(_ sender: Any) {
        guard let config = SyncAppConfig.findById(id: "WEBAPP_follow_twitter"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    
    
    @IBOutlet weak var telegramContainer: UIView!
    @IBOutlet weak var telegramButton: UIButton!
    @IBAction func telegramAction(_ sender: Any) {
        guard let config = SyncAppConfig.findById(id: "WEBAPP_follow_telegram"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    @IBOutlet weak var linkedinContainer: UIView!
    @IBOutlet weak var linkedinButton: UIButton!
    @IBAction func linkedinAction(_ sender: Any) {
        guard let config = SyncAppConfig.findById(id: "WEBAPP_follow_linkedin"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    
    
    @IBOutlet weak var youtubeContainer: UIView!
    @IBOutlet weak var youtubeButton: UIButton!
    @IBAction func youtubeAction(_ sender: Any) {
        guard let config = SyncAppConfig.findById(id: "WEBAPP_follow_youtube"), config.getValue(defaultValue: "") != "" else{
           return
        }
        
        if let url = URL(string: config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    
    func setupSize()  {
        if Device.isPad{
            let width = self.view.frame.width/1.5
            let finalSize = self.view.frame.width-width
            self.stackViewLeftConstraint.constant = finalSize/2
        }
    }
    
    
    @IBOutlet weak var imageContainer: UIView!
    @IBOutlet weak var aboutTextLabel: AttributedLabel!
    @IBOutlet weak var aboutDetailConstraintHeight: NSLayoutConstraint!
    @IBOutlet weak var aboutContainer: UIView!
    @IBOutlet weak var image: UIImageView!
    
  
    @IBOutlet weak var version: UILabel!
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupNavBarTitles() {
        
        
        let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
        topBarTitle.frame = rect
        topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)
        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5
        
        
        
        topBarTitle.text = "About us".localized
        
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    
    func setupNavBarButtons() {
        
        let _color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)

        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: Colors.Appearance.darkColor)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: Colors.Appearance.darkColor)
        }
        
        
        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: _color)
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
    }
    
    @objc func onBackHandler()  {
        
        if let controller = self.navigationController{
            //controller.navigationBar.isHidden = true
            controller.popViewController(animated: true)
            ////controller.navigationBar.isHidden = false
        }else{
            self.dismiss(animated: true)
        }
        
    }
    
    
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupSize()
        
        self.view.backgroundColor = Colors.Appearance.darkColor

     
        
        self.setupNavBarTitles()
        self.setupNavBarButtons()
        
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)
        
        
        self.setupViews()
        self.setupImage()
        
        
        
        //First get the nsObject by defining as an optional anyObject
        let nsObject: AnyObject? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as AnyObject
        //Then just cast the object as a String, but be careful, you may want to double check for nil
        let version = nsObject as! String
        
        self.version.text = "\("Version".localized): "+version
        
    }
    
    
    func setupImage() {
        
        if let img = UIImage(named: "splash_screen") {
            self.image.image = img
        }
    }
    
    
    func setupViews() {
        
        
        
        aboutLabel.initBolodFont()
    
        //self.stackview.distribution = .fillProportionally
        
        scrollView.parallaxHeader.view = self.imageContainer
        scrollView.parallaxHeader.height = self.imageView.frame.height;
        scrollView.parallaxHeader.mode = .fill;
        scrollView.parallaxHeader.minimumHeight = 0;
        
    
        
        self.setupAbout()
        self.setupButtons()
        self.setupAddress()
        
      
    }
    
    func setupAbout(){
        
        
        aboutLabel.text = "About us".localized
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_about_us"), config.getValue(defaultValue: "") != "" else{
            return
        }
        
        let htmlText = config.getValue(defaultValue: AppConfig.APP_NAME).toHtml()
        aboutTextLabel.numberOfLines = 90000
        aboutTextLabel.attributedText = htmlText
        aboutTextLabel.sizeToFit()
        
        
        DispatchQueue.main.asyncAfter(wallDeadline: .now()+2) {
            
            let size = CGSize(width: self.aboutTextLabel.frame.width, height: self.aboutTextLabel.frame.height)
            let nsize = self.aboutTextLabel.sizeThatFits(size)
            
            self.aboutTextLabel.attributedText = htmlText
            self.aboutTextLabel.heightAnchor.constraint(equalToConstant: nsize.height).isActive = true
          
            self.aboutContainer.layoutIfNeeded()
            self.view.layoutIfNeeded()
            
        }
        
        
        aboutTextLabel.onClick = { label, detection in
            
            switch detection.type {
            case .link(let url):
                UIApplication.shared.openURL(url)
            default:
                break
            }
        }
        
        
    }
    
    func setupAddress() {
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_contact_address"), config.getValue(defaultValue: "") != "" else{
            self.addressContainer.isHidden = true
            return
        }
        
        self.addressLabel.initDefaultFont()
        self.addressLabel.text  = " \(config.getValue(defaultValue: ""))"
        self.addressLabel.setLeftIcon(image: UIImage(named: "location-1")!)
      
        
        self.addressLabel.isUserInteractionEnabled = true
        let gestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(addressClicked))
        self.addressLabel.addGestureRecognizer(gestureRecognizer1)
        
    }
    
    @objc func addressClicked()  {
        
        guard let config = SyncAppConfig.findById(id: "WEBAPP_contact_address"), config.getValue(defaultValue: "") != "" else{
            self.addressContainer.isHidden = true
            return
        }
        
    
        if let url = URL(string: "http://maps.apple.com/?address="+config.getValue(defaultValue: "")), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
    }
  
    
    func setupButtons(){
     
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_contact_phone"), config.getValue(defaultValue: "") != ""{
            
            let phone = Utils.formatPhone(string: config.getValue(defaultValue: ""))
            let result = phone.isValid(regex: .phone)
                                          
            self.phoneButton.setupButton().setCustomText(string: phone)
            
        }else{
            self.phoneContainer.isHidden = true
        }
        
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_contact_email"), config.getValue(defaultValue: "") != ""{
            self.emailButton.setupButton().setCustomText(string: config.getValue(defaultValue: ""))
        }else{
            self.emailContainer.isHidden = true
        }
        
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_follow_facebook"), config.getValue(defaultValue: "") != ""{
            self.facebookButton.setupButton().setCustomText(string:  findUsernameURI(string: config.getValue(defaultValue: "")) )
            self.facebookButton.tintColor = Utils.hexStringToUIColor(hex: "#4267B2")
            self.facebookButton.titleLabel?.tintColor = UIColor(named: "label-text-color")
        }else{
            self.facebookContainer.isHidden = true
        }
        
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_follow_twitter"), config.getValue(defaultValue: "") != ""{
            self.twitterButton.setupButton().setCustomText(string: findUsernameURI(string: config.getValue(defaultValue: ""))  )
            self.twitterButton.tintColor = Utils.hexStringToUIColor(hex: "#1DA1F2")
            self.twitterButton.titleLabel?.tintColor = UIColor(named: "label-text-color")
        }else{
            self.twitterContainer.isHidden = true
        }
        
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_follow_instagram"), config.getValue(defaultValue: "") != ""{
            self.instagramButton.setupButton().setCustomText(string: findUsernameURI(string: config.getValue(defaultValue: "")) )
            self.instagramButton.tintColor = Utils.hexStringToUIColor(hex: "#C13584")
            self.instagramButton.titleLabel?.tintColor = UIColor(named: "label-text-color")
        }else{
            self.instagramContainer.isHidden = true
        }
        
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_follow_telegram"), config.getValue(defaultValue: "") != ""{
            self.telegramButton.setupButton().setCustomText(string: findUsernameURI(string: config.getValue(defaultValue: "")) )
            self.telegramButton.tintColor = Utils.hexStringToUIColor(hex: "#2AABEE")
            self.telegramButton.titleLabel?.tintColor = UIColor(named: "label-text-color")
        }else{
            self.telegramContainer.isHidden = true
        }
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_follow_youtube"), config.getValue(defaultValue: "") != ""{
            self.youtubeButton.setupButton().setCustomText(string: "Youtube".localized )
            self.youtubeButton.tintColor = Utils.hexStringToUIColor(hex: "#FF0000")
            self.youtubeButton.titleLabel?.tintColor = UIColor(named: "label-text-color")
        }else{
            self.youtubeContainer.isHidden = true
        }
        
        if let config = SyncAppConfig.findById(id: "WEBAPP_follow_linkedin"), config.getValue(defaultValue: "") != ""{
            self.linkedinButton.setupButton().setCustomText(string: findUsernameURI(string: config.getValue(defaultValue: "")) )
            self.linkedinButton.tintColor = Utils.hexStringToUIColor(hex: "#0077b5")
            self.linkedinButton.titleLabel?.tintColor = UIColor(named: "label-text-color")
        }else{
            self.linkedinContainer.isHidden = true
        }
       
    
    }
  
   
    func findUsernameURI(string: String) -> String{
        
        let arr1 = string.components(separatedBy: "/")
        if let last =  arr1.last{
            
            let arr2 = last.components(separatedBy: "@")
            if let last =  arr2.last{
                return last
            }
            
            return last
        }
        
        let arr3 = string.components(separatedBy: "@")
        if let last =  arr3.last{
            return last
        }
        
       return string
    }
    
}

extension UIButton{
    func setupButton() -> UIButton{
        self.titleLabel?.textAlignment = .left
        self.imageView?.image?.withRenderingMode(.alwaysTemplate)
        return self
    }
}

