import Foundation
import Darwin

/// Date dei file (creazione, modifica, ultimo accesso) e come cambiarle, sul modello di BulkFileChanger.
public enum FileDateKind: Int, CaseIterable, Codable {
    case created, modified, accessed

    public var title: String {
        switch self {
        case .created: return "Creato"
        case .modified: return "Modificato"
        case .accessed: return "Accesso"
        }
    }
}

public enum DateSource: Int, CaseIterable, Codable {
    case created, modified, accessed, exif

    public var title: String {
        switch self {
        case .created: return "Creato"
        case .modified: return "Modificato"
        case .accessed: return "Accesso"
        case .exif: return "Scatto (EXIF / video)"
        }
    }
}

public enum TimeStep: Int, CaseIterable, Codable {
    case seconds, minutes, hours, days

    public var title: String {
        switch self {
        case .seconds: return "Secondi"
        case .minutes: return "Minuti"
        case .hours: return "Ore"
        case .days: return "Giorni"
        }
    }

    public var seconds: TimeInterval {
        switch self {
        case .seconds: return 1
        case .minutes: return 60
        case .hours: return 3600
        case .days: return 86400
        }
    }
}

public enum TriState: Int, Codable { case unchanged, on, off }

public struct FileDates: Equatable {
    public var created: Date?
    public var modified: Date?
    public var accessed: Date?
    public var exif: Date?

    public init(created: Date? = nil, modified: Date? = nil, accessed: Date? = nil, exif: Date? = nil) {
        self.created = created
        self.modified = modified
        self.accessed = accessed
        self.exif = exif
    }

    public subscript(kind: FileDateKind) -> Date? {
        get {
            switch kind {
            case .created: return created
            case .modified: return modified
            case .accessed: return accessed
            }
        }
        set {
            switch kind {
            case .created: created = newValue
            case .modified: modified = newValue
            case .accessed: accessed = newValue
            }
        }
    }

    public func value(_ s: DateSource) -> Date? {
        switch s {
        case .created: return created
        case .modified: return modified
        case .accessed: return accessed
        case .exif: return exif
        }
    }

    public static func read(_ url: URL) -> FileDates {
        // Le URL ricordano i valori già letti: dopo una modifica vanno riletti dal disco.
        var url = url
        url.removeAllCachedResourceValues()
        let v = try? url.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey, .contentAccessDateKey])
        return FileDates(created: v?.creationDate, modified: v?.contentModificationDate, accessed: v?.contentAccessDate)
    }
}

public struct DateChangeSettings {
    public struct Field {
        public var setDate = false
        public var date = Date()
        public var setTime = false
        public var time = Date()
        public var add = false
        public var amount = 0
        public var step = TimeStep.hours
        public init() {}
    }

    public var fields: [FileDateKind: Field] = [.created: Field(), .modified: Field(), .accessed: Field()]
    /// Le date e ore scritte sono in GMT invece che nell'ora locale.
    public var gmt = false
    /// Modalità sequenza: il file n riceve n volte la quantità di "Aggiungi" (il primo nessuna).
    public var sequence = false
    public var copyFrom: DateSource?
    public var copyTo: Set<FileDateKind> = [.created, .accessed]
    public var hidden = TriState.unchanged
    public var locked = TriState.unchanged

    public init() {}

    public var changesDates: Bool {
        copyFrom != nil || fields.values.contains { $0.setDate || $0.setTime || ($0.add && $0.amount != 0) }
    }
}

public enum DateChanger {
    /// Le nuove date di un file: prima giorno, ora e "Aggiungi" su ogni data, poi "Copia orario da"
    /// (che copia il valore già corretto: "modifica -7 ore e metti la creazione uguale" dà due date uguali).
    public static func newDates(_ d: FileDates, index: Int, settings s: DateChangeSettings) -> FileDates {
        var cal = Calendar(identifier: .gregorian)
        if s.gmt { cal.timeZone = TimeZone(identifier: "UTC")! }
        var out = d
        for kind in FileDateKind.allCases {
            guard let f = s.fields[kind], var v = d[kind] else { continue }
            if f.setDate || f.setTime {
                var c = cal.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: v)
                if f.setDate {
                    let n = cal.dateComponents([.year, .month, .day], from: f.date)
                    c.year = n.year; c.month = n.month; c.day = n.day
                }
                if f.setTime {
                    let n = cal.dateComponents([.hour, .minute, .second], from: f.time)
                    c.hour = n.hour; c.minute = n.minute; c.second = n.second; c.nanosecond = 0
                }
                v = cal.date(from: c) ?? v
            }
            if f.add && f.amount != 0 {
                let times = s.sequence ? Double(index) : 1
                v = v.addingTimeInterval(Double(f.amount) * f.step.seconds * times)
            }
            out[kind] = v
        }
        if let src = s.copyFrom, let v = out.value(src) {
            for kind in s.copyTo { out[kind] = v }
        }
        return out
    }

    /// Scrive le date sul disco. La creazione va per ultima: se la modifica è più vecchia, macOS sposta anche la creazione.
    public static func apply(_ url: URL, from old: FileDates, to new: FileDates, hidden: TriState, locked: TriState) throws {
        var values = URLResourceValues()
        if locked == .off { values.isUserImmutable = false }
        if values.isUserImmutable != nil {
            var u = url
            try u.setResourceValues(values)
        }
        if new.modified != old.modified || new.accessed != old.accessed {
            let a = new.accessed ?? old.accessed ?? Date()
            let m = new.modified ?? old.modified ?? Date()
            var times = [timespec(a), timespec(m)]
            if utimensat(AT_FDCWD, url.path, &times, AT_SYMLINK_NOFOLLOW) != 0 {
                throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
            }
        }
        var last = URLResourceValues()
        // Spostare indietro la modifica trascina con sé la creazione: in quel caso la si riscrive sempre.
        if let c = new.created, c != old.created || new.modified != old.modified { last.creationDate = c }
        if hidden != .unchanged { last.isHidden = hidden == .on }
        if locked == .on { last.isUserImmutable = true }
        if !last.allValues.isEmpty {
            var u = url
            try u.setResourceValues(last)
        }
    }

    private static func timespec(_ d: Date) -> Darwin.timespec {
        let t = d.timeIntervalSince1970
        let s = floor(t)
        return Darwin.timespec(tv_sec: Int(s), tv_nsec: Int((t - s) * 1_000_000_000))
    }
}
