//
//  CountDownView.swift
//  NSApplication1.8
//
//  Created by Amine  on 5/13/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import Foundation
import UIKit

class CountDownView : UIView{
    
    
    required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
     }
     
     override init(frame: CGRect) {
         super.init(frame: frame)
     }
     
    
    
    var daysCounter: EdgeLabel?
    var hoursCounter: EdgeLabel?
    var minutesCounter: EdgeLabel?
    var secondsCounter: EdgeLabel?
    
    var days = 0
    var hours = 0
    var minutes = 0
    var seconds = 0
       

    func setup( width: CGFloat, height: CGFloat) {
        
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.alignment = .fill
        stackView.distribution = .fill
        stackView.spacing = CGFloat(0)
        stackView.backgroundColor = .orange
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.backgroundColor = .clear
        
        
        
        stackView.heightAnchor.constraint(equalToConstant: height).isActive = true
       
        addSubview(stackView)
        
        
        var constraints = [NSLayoutConstraint]()
               
               constraints.append(NSLayoutConstraint(
                   item: stackView,
                   attribute: NSLayoutConstraint.Attribute.right,
                   relatedBy: NSLayoutConstraint.Relation.equal,
                   toItem: self,
                   attribute: NSLayoutConstraint.Attribute.right,
                   multiplier: 1, constant: 0)
               )
               
               constraints.append(NSLayoutConstraint(
                   item: stackView,
                   attribute: NSLayoutConstraint.Attribute.top,
                   relatedBy: NSLayoutConstraint.Relation.equal,
                   toItem: self,
                   attribute: NSLayoutConstraint.Attribute.top,
                   multiplier: 1, constant: 0)
               )
               
               constraints.append(NSLayoutConstraint(
                   item: stackView,
                   attribute: NSLayoutConstraint.Attribute.bottom,
                   relatedBy: NSLayoutConstraint.Relation.equal,
                   toItem: self,
                   attribute: NSLayoutConstraint.Attribute.bottom,
                   multiplier: 1, constant: 0)
               )
               
               constraints.append(NSLayoutConstraint(
                   item: stackView,
                   attribute: NSLayoutConstraint.Attribute.left,
                   relatedBy: NSLayoutConstraint.Relation.equal,
                   toItem: self,
                   attribute: NSLayoutConstraint.Attribute.left,
                   multiplier: 1, constant: 0)
               )
               
              
        self.addConstraints(constraints)
        
    
        
        self.daysCounter = EdgeLabel()
        self.hoursCounter = EdgeLabel()
        self.minutesCounter = EdgeLabel()
        self.secondsCounter = EdgeLabel()
        
        
        self.daysCounter?.sizeToFit()
        self.hoursCounter?.sizeToFit()
        self.minutesCounter?.sizeToFit()
        self.secondsCounter?.sizeToFit()
        
        self.daysCounter?.initBolodFont()
        self.hoursCounter?.initBolodFont()
        self.minutesCounter?.initBolodFont()
        self.secondsCounter?.initBolodFont()
        
        self.daysCounter?.numberOfLines = 1
        self.hoursCounter?.numberOfLines = 1
        self.minutesCounter?.numberOfLines = 1
        self.secondsCounter?.numberOfLines = 1
        
        
        self.daysCounter?.textColor = .white
        self.hoursCounter?.textColor = .white
        self.minutesCounter?.textColor = .white
        self.secondsCounter?.textColor = .white
        

        
        self.daysCounter?.translatesAutoresizingMaskIntoConstraints = false
        self.hoursCounter?.translatesAutoresizingMaskIntoConstraints = false
        self.minutesCounter?.translatesAutoresizingMaskIntoConstraints = false
        self.secondsCounter?.translatesAutoresizingMaskIntoConstraints = false
        
        self.daysCounter?.roundedCorners(radius: 3)
        self.hoursCounter?.roundedCorners(radius: 3)
        self.minutesCounter?.roundedCorners(radius: 3)
        self.secondsCounter?.roundedCorners(radius: 3)
        
         let dots1 = EdgeLabel()
        dots1.text = ":"
        dots1.textAlignment = .center
        dots1.textColor = .white
        dots1.widthAnchor.constraint(equalToConstant: CGFloat(5)).isActive = true
    
        
        let dots2 = EdgeLabel()
        dots2.text = ":"
        dots2.textAlignment = .center
        dots2.textColor = .white
        dots2.widthAnchor.constraint(equalToConstant: CGFloat(5)).isActive = true
        
        
        let dots3 = EdgeLabel()
        dots3.text = ":"
        dots3.textAlignment = .center
        dots3.textColor = .white
        dots3.widthAnchor.constraint(equalToConstant: CGFloat(5)).isActive = true
        
        
        self.daysCounter!.text = "\("days".localized)"
        self.hoursCounter!.text = "00"
        self.minutesCounter!.text = "00"
        self.secondsCounter!.text = "00"

        
        self.daysCounter!.textAlignment = .center
        self.hoursCounter!.textAlignment = .center
        self.minutesCounter!.textAlignment = .center
        self.secondsCounter!.textAlignment = .center
        
        
        let label = EdgeLabel()
        label.text = "\("End at:".localized) "
        label.textAlignment = .center
        label.textColor = .white
        label.initBolodFont()
        stackView.addArrangedSubview(label)

        
        stackView.addArrangedSubview(daysCounter!)
        stackView.addArrangedSubview(hoursCounter!)
        stackView.addArrangedSubview(dots2)
        stackView.addArrangedSubview(minutesCounter!)
        stackView.addArrangedSubview(dots3)
        stackView.addArrangedSubview(secondsCounter!)
        
    
       
        secondsCounter?.heightAnchor.constraint(equalToConstant: height).isActive = true
        secondsCounter?.widthAnchor.constraint(equalToConstant: 35).isActive = true
        
        minutesCounter?.heightAnchor.constraint(equalToConstant: height).isActive = true
        minutesCounter?.widthAnchor.constraint(equalToConstant: 35).isActive = true
        
        hoursCounter?.heightAnchor.constraint(equalToConstant: height).isActive = true
        hoursCounter?.widthAnchor.constraint(equalToConstant: 35).isActive = true
        
        daysCounter?.heightAnchor.constraint(equalToConstant: height).isActive = true
        //daysCounter?.widthAnchor.constraint(equalToConstant: 50).isActive = true
     
        
        setTime(date_end: date_end)
        
     }
    
    
    
    //custom spontadeal
       var date_end = ""
      
       func setTime(date_end: String) -> CountDownView{
           
           
           self.date_end = date_end
           
           if let timer = getDiffTime(date_end_UTC: date_end) {
               
            self.days = timer.days
            self.hours = timer.hours
            self.minutes = timer.minutes
            self.seconds = timer.seconds
            
               if(isLessThan1Second(components: timer.dateComponents!)){
                   
                    self.daysCounter!.text = "00 \("days".localized)"
                    self.hoursCounter!.text = "00"
                    self.minutesCounter!.text = "00"
                    self.secondsCounter!.text = "00"
                   
                   return self
               }
               
               
               if(timer.days<10 && timer.days>=0){
                   self.daysCounter!.text = "0\(timer.days) \("days".localized)"
               }else{
                   self.daysCounter!.text = "\(timer.days) \("days".localized)"
               }
           
               
               if(timer.hours<10 && timer.hours>=0){
                   self.hoursCounter!.text = "0\(timer.hours)"
               }else{
                   self.hoursCounter!.text = "\(timer.hours)"
               }
               
               
               if(timer.minutes<10 && timer.minutes>=0){
                   self.minutesCounter!.text = "0\(timer.minutes)"
               }else{
                   self.minutesCounter!.text = "\(timer.minutes)"
               }
               
             
                if(timer.seconds<10 && timer.seconds>=0){
                    self.secondsCounter!.text = "0\(timer.seconds)"
                }else{
                    self.secondsCounter!.text = "\(timer.seconds)"
                }
            
            let anim = UIAnimation(view: self.secondsCounter!)
            anim.zoomIn(duration: 0.3)
               
               
               Utils.printDebug("CountDownTimer days:\(timer.days) - hours: \(timer.hours) - minutes: \(timer.minutes)  - seconds: \(timer.seconds)")
               
               
               if isLessThan1Second(components: timer.dateComponents!){
                   Utils.printDebug("\(timer.dateComponents!)")
                   self.stopTimer()
               }
               
           }else{
               
           }
           
        
         return self
           
       }
       
       var timer = Timer()
       
       func runTimer() {
           timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
       }
       
      
       func stopTimer() {
           timer.invalidate()
       }
       
       @objc func updateTimer() {
           self.setTime(date_end: self.date_end)
       }
    
    
    
    
    
    func getDiffTime(date_end_UTC: String) -> MyTime?{
        
         let dateRangeStart = Date()
        
        if let dateEnd = DateUtils.convertToDate(dateUTC: date_end_UTC) {
            
             let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: dateRangeStart, to: dateEnd)
            
            var time = MyTime()
            time.days = components.day!
            time.hours = components.hour!
            time.minutes = components.minute!
            time.seconds = components.second!
            time.dateComponents = components
            
            return time
            
        }
        
        return nil
    }
    
    
    func isLessThan1Second(components: DateComponents) -> Bool {
           
           if components.year!<0{
               return true
           }
           
           if components.month!<0{
               return true
           }
           
           if components.day!<0{
               return true
           }
           
           if components.hour!<0{
               return true
           }
           
           if components.minute!<0{
               return true
           }
           
           if components.second!<0{
               return true
           }
           
           guard components.year! >= 0 else { return false }
           guard components.month! >= 0 else { return false }
           guard components.day! >= 0 else { return false }
           guard components.hour! >= 0  else { return false }
           guard components.minute! >= 0  else { return false }
           guard components.second! < 0  else { return false }
           
          
           return true
       }
    
    
}


struct MyTime {
    init() {
        self.days = 0
        self.hours = 0
        self.minutes = 0
        self.seconds = 0
        self.dateComponents = nil
    }
    var days: Int
    var hours: Int
    var minutes: Int
    var seconds: Int
    var dateComponents: DateComponents?
}
