//
//  SHCloudManager.swift
//  ShorthandMaster
//
//  Created by 明津李 on 2020/8/31.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit
import CloudKit

class SHCloudManager: NSObject {

    @objc static let shared = SHCloudManager()
    
    private override init() {}
    
    let recordName = "Recording"
    
    lazy var container = CKContainer.default()

    lazy var resultRecords:[CKRecord] = []
    
    typealias handler = ((Bool) -> ())
    var statusHandler: handler?
    
    func cheakAccountStatus(_ handler:@escaping handler){

        statusHandler = handler

        let container = CKContainer.default()
        container.accountStatus { (status, statusError) in

            if let error = statusError {
                self.statusHandler?(false)
                print("\(error.localizedDescription)")
            }else{
                switch status {
                case .available:
                    self.statusHandler?(true)
                    break;
                default:
                    self.statusHandler?(false)
                    break;
                }
            }
        }
    }
    
    func getAllRecordDataSource(){
        
        let dateBase = container.publicCloudDatabase
        
        let predicate = NSPredicate.init(value: true)
        let query = CKQuery.init(recordType: recordName, predicate: predicate)

        dateBase.perform(query, inZoneWith: nil) { (records, queryError) in

            if let error = queryError {
                print("\(error.localizedDescription)")
            }else{
                self.resultRecords = records!
            }
        }
    }
    
    func addNewRecord(_ model: SHRecordModel){
        
        let documentsFile = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first)!.appending(model.pathFile)
        let url = URL.init(fileURLWithPath: documentsFile)
        let asset = CKAsset.init(fileURL: url)
        
        let dateBase = container.publicCloudDatabase
        
        let newRecording = CKRecord.init(recordType: recordName)
        newRecording.setValue(model.address, forKey: "title")
        newRecording.setValue(model.address, forKey: "address")
        newRecording.setValue(model.txt, forKey: "content")
        newRecording.setValue(model.createDate, forKey: "createTime")
        newRecording.setValue(0, forKey: "delete")
        newRecording.setValue(asset, forKey: "recordAsset")
                
        dateBase.save(newRecording) { (subscription, saveError) in
            if let error = saveError {
                print("\(error.localizedDescription)")
            }else{
                
            }
        }
    }
    
    func modifyRecord(){
        let dateBase = container.publicCloudDatabase
        
        let record = resultRecords.first

        dateBase.fetch(withRecordID: record!.recordID) { (record, fetchError) in
            
            if let error = fetchError {
                print("\(error.localizedDescription)")
            }else {
                record![""] = ""
                dateBase.save(record!) { (saveRecord, saveError) in
                    
                    if let error = saveError {
                        print("\(error.localizedDescription)")
                    }else{
                        
                    }
                }
            }
        }
    }
    
    func deleteRecord(){
        
        let dateBase = container.publicCloudDatabase
        
        let record = resultRecords.first
        
        dateBase.delete(withRecordID: record!.recordID) { (recordID, deleteError) in
            
            if let error = deleteError {
                print("\(error.localizedDescription)")
            }else{
                
            }
        }
    }
}
