//
//  DataModel.swift
//  Comedores Sociales
//
//  Created by Hector Carrion on 11/8/20.
//

import Foundation

let serverAddress: String = "http://161.35.60.201/"

class Authentication: Codable {
    var username: String
    var password: String
    
    init(email: String, password: String) {
        self.username = email
        self.password = password
    }
    
    func isComplete() -> Bool {
        if username != "" && password != "" {
            return true
        } else {
            return false
        }
    }
}

class Registration: Codable {
    var username: String
    var password: String
    var nombre: String
    var urbanizacion: String
    var calle: String
    var pueblo: String
    var cpostal: String
    var telefono: String
    var correo: String
    var organizacion: String?
    var puesto: String?
    
    init(email: String, password: String, name: String, urb: String, street: String, city: String, zip: String, phone: String, org: String? = nil, position: String? = nil) {
        if org != "" {
            self.username = email
            self.password = password
            self.nombre = name
            self.urbanizacion = urb
            self.calle = street
            self.pueblo = city
            self.cpostal = zip
            self.telefono = phone
            self.correo = email
            self.organizacion = org
            self.puesto = position
            
        } else {
            self.username = email
            self.password = password
            self.nombre = name
            self.urbanizacion = urb
            self.calle = street
            self.pueblo = city
            self.cpostal = zip
            self.telefono = phone
            self.correo = email
            self.organizacion = nil
            self.puesto = nil
        }
    }
    
    func isComplete() -> Bool {
        if username != "" && password != "" && nombre != "" && urbanizacion != "" && calle != "" && pueblo != "" && cpostal != "" && telefono != "" && correo != "" {
            return true
        } else {
            return false
        }
    }
}


class LoginViewModel: ObservableObject {
    @Published var response: Bool?
    
    func changeResponse(response: Bool) {
        self.response = response
    }
    
    func login(data: Authentication) {
        
        let service = "login.php"
        guard let encodedData = try? JSONEncoder().encode(data)
        else {
            print("Failed to encode login request")
            return
        }
        
        //print("JSON to send:", String(data: encodedData, encoding: .utf8)!)
        
        let url = URL(string: serverAddress + service)!
        var request = URLRequest(url: url)
        request.setValue("applogin/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = encodedData
        
        URLSession.shared.dataTask(with: request) {data, response, error in
            
            //handle result here
            guard let data = data
            else {
                print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
                return
            }
            print(response ?? "No response")
            print("Recieved data:", data)
            print(error ?? "No error")
            
            if let httpResponse = response as? HTTPURLResponse {
                DispatchQueue.main.async {
                    if httpResponse.statusCode == 200 {
                        self.changeResponse(response: true)
                    } else {
                        self.changeResponse(response: false)
                    }
                    
                }
            }
            
        }.resume()
    }
}

class RegisterViewModel: ObservableObject {
    @Published var response: Bool?
    
    func changeResponse(response: Bool) {
        self.response = response
    }
    
    func register(data: Registration) {
        
        let service = "signup.php"
        guard let encodedData = try? JSONEncoder().encode(data)
        else {
            print("Failed to encode register request")
            return
        }
        
        print("Reg JSON to send:", String(data: encodedData, encoding: .utf8)!)
        
        let url = URL(string: serverAddress + service)!
        var request = URLRequest(url: url)
        request.setValue("appregister/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = encodedData
        
        URLSession.shared.dataTask(with: request) {data, response, error in
            
            //handle result here
            guard let data = data
            else {
                print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
                return
            }
            print(response ?? "No response")
            print("Recieved data:", data)
            print(error ?? "No error")
            
            if let httpResponse = response as? HTTPURLResponse {
                DispatchQueue.main.async {
                    if httpResponse.statusCode == 200 {
                        self.changeResponse(response: true)
                    } else {
                        self.changeResponse(response: false)
                    }
                }
            }
        }.resume()
    }
}
