//
//  DateHelper.swift
//  Plugin
//
//  Created by Francisco Guerrero Escamilla on 04/05/24.
//  Copyright © 2024 Max Lynch. All rights reserved.
//

import Foundation

protocol DateHelperProtocol {
  func getDateFromString(stringDate: String) -> Date?
  func getISO8601StringDate(date: Date, timeZone: TimeZone) -> String
}

struct DateHelper: DateHelperProtocol {

  private let dateISOFormatterDateLocal: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: Locale.preferredLanguages[0])
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    return dateFormatter
  }()

  private let dateIonicFormatterDate: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: Locale.preferredLanguages[0])
    dateFormatter.dateFormat = "yyyy-MM-dd"
    return dateFormatter
  }()

  func getDateFromString(stringDate: String) -> Date? {
    return dateIonicFormatterDate.date(from: stringDate)
  }

  func getISO8601StringDate(date: Date, timeZone: TimeZone = .current) -> String {
    let dateFormat = dateISOFormatterDateLocal
    dateFormat.timeZone = timeZone
    let dateString: String = dateFormat.string(from: date)
    let timeZoneHours: Int = offsetInHours(timeZone: timeZone)
    let timeHoursString: String = String(format: "%02d", abs(timeZoneHours))
    let stringMinutes: String = String(format: "%02d", abs(minutes(timeZone: timeZone)))
    let toReturn: String = "\(dateString)\(timeZoneHours >= 0 ? "+" : "-")\(timeHoursString):\(stringMinutes)"
    return toReturn
  }

  private func offsetInHours(timeZone: TimeZone = .current) -> Int {
    let hours = (timeZone.secondsFromGMT()) / (3600)
    return hours
  }

  private func minutes(timeZone: TimeZone = TimeZone.current) -> Int {
    let minutes = abs((timeZone.secondsFromGMT() % 3600) / 60)
    return minutes
  }
}
