//
//  FlockeLoader.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 13.09.18.
//  Copyright © 2018 Julian-Steffen Müller. All rights reserved.
//

import Foundation
import Disk

extension Notification.Name {
    static let FlockeWSDeleteFinished = Notification.Name("flockeWSDeleteFinished")
    static let FlockeWSAddFinished = Notification.Name("flockeWSAddFinished")
}

class FlockeWS {
    @objc enum ERROR_STATE : Int {
        case NO_ERROR
        case REQUEST_FAILED
    }
    
    static func fetchEntries(for parent: FlockeEntryID) {
        guard let fetchEntriesURL = URL.init(string: "http://flocke.mueller.haus:8081/entry/parent/\(parent)") else {
            print("FETCH ENTRIES: Creating URL fails")
            return
        }

        let task = URLSession.shared.dataTask(with: fetchEntriesURL) { (data, resp, err) in
            if (err == nil) {
                let consoles : [FlockeEntry] = try! JSONDecoder().decode([FlockeEntry].self, from: data!)
                
                DispatchQueue.main.async {
                    GameCollection.shared.updateGameItems(items: consoles, with: parent)
                }
            }
        }
        task.resume()
    }
    
    static func fetchAttachment(attachment attachmentId : AttachmentID) {
        guard let fetchAttachmentURL = URL.init(string: "http://flocke.mueller.haus:8081/attachment/\(attachmentId)") else {
            print("FETCH ATTACHMENT: Creating URL fails")
            return
        }
        
        URLSession.shared.dataTask(with: fetchAttachmentURL) { (data, resp, err) in
            if (err == nil) {
                let attachment : Attachment = try! JSONDecoder().decode(Attachment.self, from: data!)
                
                
                DispatchQueue.main.async {
                    GameCollection.shared.updateAttachment(attachment: attachment)
                }
            }
            
        }.resume()
    }
    
    static func deleteEntry(by entry: FlockeEntryID) {
        guard let flockeDeleteEntryURL = URL.init(string: "http://flocke.mueller.haus:8081/entry/\(entry)") else {
            print("DELETE ENTRY: Creating URL fails")
            return
        }
        
        var req = URLRequest.init(url: flockeDeleteEntryURL)
        req.httpMethod = "DELETE"
        
        URLSession.shared.dataTask(with: req) { (data, resp, err) in
            if (err == nil) {
                DispatchQueue.main.async {
                    //TODO GameCollection Update
                    NotificationCenter.default.post(name: .FlockeWSDeleteFinished, object: nil)
                }
            }
        }.resume()
    }
    
    static func deleteParents(entry entryID : FlockeEntryID, parents : [FlockeEntryID]) {
        print("DELETE PARENTS WS \(entryID) - \(parents)")
        
        let addJSON : NSMutableDictionary = NSMutableDictionary()
        addJSON.setValue(entryID, forKey: "id")
        addJSON.setValue(parents, forKey: "parents")
        
        do {
            let jsonBodyData = try JSONSerialization.data(withJSONObject: addJSON, options: [])
            let jsonBodyString = String(data: jsonBodyData, encoding: .utf8) ?? "{}"
            print(jsonBodyString)
            
            let connector : FlockeConnector = FlockeConnector(url: "http://flocke.mueller.haus:8081/entry/deleteParents",
                                                              requestType: "PUT",
                                                              bodyDict: addJSON) { (data, resp, err) in
//                DispatchQueue.main.async {
//                    //NOP
//                }
            }
            
            connector.doRequest()
        }catch {
            return;
        }
        
        return;
    }
    
    
    static func addEntry(name : String, consoleID : FlockeEntryID, isVideogame : Bool, isOnWishlist : Bool) {
        print("ADD WS \(name) \(isVideogame) \(isOnWishlist)")
        
        var parents : [String] = [consoleID]
        
        if (isVideogame) {
            parents.append(GameCollection.videogameID)
        }else{
            parents.append(GameCollection.accessoryID)
        }
        
        if isOnWishlist {
            parents.append(GameCollection.wishlistID)
        }
        
        let addJSON : NSMutableDictionary = NSMutableDictionary()
        addJSON.setValue(name, forKey: "name")
        addJSON.setValue(parents, forKey: "parents")

        let connector : FlockeConnector = FlockeConnector(url: "http://flocke.mueller.haus:8081/entry/",
                                                          requestType: "POST",
                                                          bodyDict: addJSON) { (data, resp, err) in
            var requestError = FlockeWS.ERROR_STATE.NO_ERROR
            
            if (err != nil) { requestError = FlockeWS.ERROR_STATE.REQUEST_FAILED }
            
            
            DispatchQueue.main.async {
                let userInfo:[String: FlockeWS.ERROR_STATE] = ["error_state": requestError]
                NotificationCenter.default.post(name: .FlockeWSAddFinished, object: nil, userInfo: userInfo)
            }
        }

        connector.doRequest()
    }
}
