//
//  AppointmentsViewController.swift
//  iPOS
//
//  Created by bbc on 20/01/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import UIKit
import EventKit
import EventKitUI

class AppointmentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MasterViewControllerDelegate, EKEventEditViewDelegate{
    
    @IBOutlet weak var tableView: UITableView!
    static var contact: Contact!
    var contactId: String?
    var isSlideButtonEnabled = true
    var shouldFetchEvents = false
    
    var calendar: EKCalendar!
    var eventStore : EKEventStore!
    var eventsList: [EKEvent] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Util.getString("Appointments")
        self.eventStore = EKEventStore()
        self.createNewButton()
        self.checkEventStoreAccessForCalendar()
        self.setDefaultLayout()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setToolbarHidden(true, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if self.shouldFetchEvents{
            self.eventsList = fetchEvents()
            
            if self.eventsList.count != State.appointments.count{
                self.reloadFromDatabase()
            }
            else{
                self.tableView.reloadData()
            }
        }
    }
    
    func reloadFromDatabase(){
        self.removeDefaultCalendar()
        self.calendar = createDefaultCalendar()
        self.createEvents()
    }
    
    func setDefaultLayout(){
        if self.isSlideButtonEnabled{
            self.setNavigationBarItem()
        }
    }
    
    private func checkEventStoreAccessForCalendar() {
        let status = EKEventStore.authorizationStatus(for: EKEntityType.event)
        
        switch status {
        // Update our UI if the user has granted access to their Calendar
        case .authorized: self.accessGrantedForCalendar()
        // Prompt the user for access to Calendar if there is no definitive answer
        case .notDetermined: self.requestCalendarAccess()
        // Display a message if the user has denied or restricted access to Calendar
        case .denied, .restricted:
            Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("Permission was not granted for Calendar"))
            self.restrictUserActions()
        @unknown default:
            break
        }
    }
    
    private func restrictUserActions(){
        self.view.isUserInteractionEnabled = false
        self.navigationItem.rightBarButtonItem = nil
    }
    
    // Prompt the user for access to their Calendar
    private func requestCalendarAccess() {
        self.eventStore.requestAccess(to: .event) {[weak self] granted, error in
            if granted {
                // Let's ensure that our code will be executed from the main queue
                DispatchQueue.main.async {
                    // The user has granted access to their Calendar; let's populate our UI with all events occuring in the next 24 hours.
                    self?.accessGrantedForCalendar()
                }
            }
            else{
                DispatchQueue.main.async {
                    self?.restrictUserActions()
                }
            }
        }
    }
    
    // This method is called when the user has granted permission to Calendar
    private func accessGrantedForCalendar() {
        // Let's get the default calendar associated with our event store
        self.removeDefaultCalendar()
        self.calendar = createDefaultCalendar()
        self.createEvents()
    }

    func createNewButton(){
        let addAppointments = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewAppointment))
        self.navigationItem.rightBarButtonItem = addAppointments
    }
    
    @objc func addNewAppointment(){
        if self.contactId == nil{
            let masterViewController = (self.storyboard?.instantiateViewController(withIdentifier: "contactsViewController") as! MasterViewController)
            masterViewController.delegate = self
            masterViewController.isSlideButtonEnabled = false
            self.navigationController?.pushViewController(masterViewController, animated: true)
        }
        else{
            addNewEventForSelectedContact()
        }
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.eventsList.count
    }
    
    func setDateLayout(appointment: Appointment) -> String{
        let myCalendar = Calendar(identifier: .gregorian)
        let startDay = myCalendar.component(.day, from: appointment.StartDate!)
        let endDay = myCalendar.component(.day, from: appointment.EndDate!)
        
        let timeInterval =  appointment.EndDate!.timeIntervalSince(appointment.StartDate!)
        let startDate = Util.DateToCompleteDateString(date: appointment.StartDate!)
        var endDate = Util.DateToTimeString(date: (appointment.StartDate!.addingTimeInterval(timeInterval)))
        
        if startDay != endDay {
            endDate = Util.DateToCompleteDateString(date: appointment.EndDate!)
            return "\(startDate) - \(endDate)"
        }
        
        return "\(startDate) - \(endDate)"
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let event = self.eventsList[indexPath.row]
        
        var appointment = AppointmentsViewController.macthEventWithAppointment(event: event)
        
        if let existingAppointment = appointment{
            cell.textLabel?.text = "\(existingAppointment.Subject!)"
            if let contact = existingAppointment.contact{
                cell.textLabel?.text?.append(" - \(contact.FirstName) \(contact.LastName)")
            }
            cell.detailTextLabel?.text = setDateLayout(appointment: existingAppointment)
        }
        else{
            appointment = AppointmentsViewController.createNewAppointment(appointment: Appointment(), event: event)
            cell.textLabel?.text = "\(appointment!.Subject!)"
            if AppointmentsViewController.contact != nil{
                cell.textLabel?.text?.append(" - \(AppointmentsViewController.contact.FirstName) \(AppointmentsViewController.contact.LastName)")
            }
            cell.detailTextLabel?.text = setDateLayout(appointment: appointment!)
        }
        return cell
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "eventViewController" {
            // Configure the destination event view controller
            let eventViewController = segue.destination as! EKEventViewController
            // Fetch the index path associated with the selected event
            let indexPath = self.tableView.indexPathForSelectedRow!
            // Set the view controller to display the selected event
            let event = self.eventsList[indexPath.row]
            eventViewController.event = event
            // Allow event editing
            eventViewController.allowsEditing = true
        }
    }

    func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
        self.dismiss(animated: true) {
            if action == .saved{
                var appointment = Appointment()
                var found = false
                for StateAppointment in State.appointments{
                    if StateAppointment.EventID == controller.event?.eventIdentifier{
                        appointment = StateAppointment
                        found = true
                        break
                    }
                }
                if !found{
                    appointment = AppointmentsViewController.createNewAppointment(appointment: Appointment(), event: controller.event!)
                    appointment.ContactId = AppointmentsViewController.contact.ContactId
                    appointment.contact = AppointmentsViewController.contact
                    State.addNewAppointment(appointment, completionHandler: { result in
                        if result == true {
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
                else{
                    appointment = AppointmentsViewController.createNewAppointment(appointment: appointment, event: controller.event!)
                    State.modifyAppointment(appointment, completionHandler: {  result in
                        if result == true {
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
            }
            else if action == .deleted{
                let appointment = AppointmentsViewController.macthEventWithAppointment(event: controller.event!)
                if let appointment = appointment{
                    State.deleteAppointment(appointment, completionHandler: { result in
                        if result == true {
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
            }
        }
    }
    
    static func macthEventWithAppointment(event: EKEvent) -> Appointment?{
        for appointment in State.appointments{
            if appointment.EventID == event.eventIdentifier{
                return appointment
            }
        }
        return nil
    }
    
    static func macthEventWithAppointment(eventIdentifier: String) -> Appointment?{
        for appointment in State.appointments{
            if appointment.EventID == eventIdentifier{
                return appointment
            }
        }
        return nil
    }
    
    static func createNewAppointment(appointment: Appointment,event: EKEvent) -> Appointment{
        appointment.StoreId = State.storeId
        appointment.StartDate = event.startDate
        appointment.EndDate = event.endDate
        appointment.Subject = event.title
        appointment.Location = event.location
        appointment.Description = event.notes
        appointment.IsAllDay = event.isAllDay
        appointment.EventID = event.eventIdentifier
        
        return appointment
    }
    
    func eventEditViewControllerDefaultCalendar(forNewEvents controller: EKEventEditViewController) -> EKCalendar {
        if let calendar = self.calendar{
            return calendar
        }
        return EKCalendar()
    }

    func createEvents(){
        self.eventsList = []
        State.LoadAppointments(contactId: self.contactId) { result in
            if result{
                for appointment in State.appointments{
                    self.addApointments(appointment: appointment)
                }
                self.eventsList = self.fetchEvents()
                self.tableView.reloadData()
                self.shouldFetchEvents = true
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
            }
        }
    }
    
    private func fetchEvents() -> [EKEvent] {
        //Create the end date components
        var sdc = DateComponents()
        sdc.month = -1
        
        var edc = DateComponents()
        edc.month = 1
        
        let startDate = Calendar.current.date(byAdding: sdc, to: Date())!
        
        let endDate = Calendar.current.date(byAdding: edc, to: Date())!
        
        // We will only search the default calendar for our events
        let calendarArray: [EKCalendar] = [self.calendar]
        
        // Create the predicate
        let predicate = self.eventStore.predicateForEvents(withStart: Calendar.current.startOfDay(for: startDate), end: Calendar.current.startOfDay(for: endDate),
calendars: calendarArray)
        
        // Fetch all events that match the predicate
        let events = self.eventStore.events(matching: predicate)
        
        return events
    }

    
    func addApointments(appointment: Appointment){
        let event:EKEvent = EKEvent(eventStore: self.eventStore)
        event.calendar = self.calendar
        
        if let title = appointment.Subject {
            event.title = title
        }
        if let startDate = appointment.StartDate {
            event.startDate = startDate
        }
        if let endDate = appointment.EndDate{
            event.endDate = endDate
        }
        if let location = appointment.Location{
            event.location = location
        }
        
        event.notes = appointment.Description
        
        do{
            try self.eventStore.save(event, span: .thisEvent, commit: true)
            appointment.EventID = event.eventIdentifier
            print("Event saved!")
        }
        catch{
            print("Error! Event not saved!" + "\(error.localizedDescription)")
        }
    }
    
    func selectedContactDelegate(contact: Contact){
        AppointmentsViewController.contact = contact
        self.addNewEventForSelectedContact()
    }
    
    func addNewEventForSelectedContact() {
        // Create an instance of EKEventEditViewController
        let eventEditViewController = EKEventEditViewController()
        
        // Set addController's event store to the current event store
        eventEditViewController.eventStore = self.eventStore
        eventEditViewController.editViewDelegate = self
        self.present(eventEditViewController, animated: true, completion: nil)
    }
    
    func removeDefaultCalendar(){
        let calendars = self.eventStore.calendars(for: .event)
        
        for calendar in calendars{
            if calendar.title == "iPOS"{
                do{
                    try self.eventStore.removeCalendar(calendar, commit: true)
                    print("iPOS deleted..")
                }
                catch{
                    print(error)
                }
            }
        }
    }
    
    func createDefaultCalendar() -> EKCalendar {
        let calendar = EKCalendar(for: .event, eventStore: eventStore)
        calendar.source = eventStore.defaultCalendarForNewEvents?.source
        calendar.title = "iPOS"
        do{
            try eventStore.saveCalendar(calendar, commit: true)
            print("iPOS created..")
        }
        catch{
            print(error)
        }
        
        return calendar
    }
}

extension AppointmentsViewController : SlideMenuControllerDelegate {
    
    func leftWillOpen() {
    }
    
    func leftDidOpen() {
    }
    
    func leftWillClose() {
    }
    
    func leftDidClose() {
    }
    
    func rightWillOpen() {
    }
    
    func rightDidOpen() {
    }
    
    func rightWillClose() {
    }
    
    func rightDidClose() {
    }
}

class EventViewController: EKEventViewController, EKEventEditViewDelegate, EKEventViewDelegate{
    
    var eventIdentifier: String!
    
    override func viewDidLoad() {
        self.delegate = self
        self.eventIdentifier = self.event.eventIdentifier
    }
    
    func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
        self.dismiss(animated: true) {
            if action == .saved{
                var appointment = Appointment()
                var found = false
                for StateAppointment in State.appointments{
                    if StateAppointment.EventID == controller.event?.eventIdentifier{
                        appointment = StateAppointment
                        found = true
                        break
                    }
                }
                if !found{
                    appointment = AppointmentsViewController.createNewAppointment(appointment: Appointment(), event: controller.event!)
                    appointment.ContactId = AppointmentsViewController.contact.ContactId
                    appointment.contact = AppointmentsViewController.contact
                    State.addNewAppointment(appointment, completionHandler: { result in
                        if result == true {
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
                else{
                    appointment = AppointmentsViewController.createNewAppointment(appointment: appointment, event: controller.event!)
                    State.modifyAppointment(appointment, completionHandler: {  result in
                        if result == true {
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
            }
            else if action == .deleted{
                let appointment = AppointmentsViewController.macthEventWithAppointment(eventIdentifier: self.eventIdentifier)
                if let appointment = appointment{
                    State.deleteAppointment(appointment, completionHandler: { result in
                        if result == true {
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
            }
        }
    }
    
    func eventViewController(_ controller: EKEventViewController, didCompleteWith action: EKEventViewAction) {
        if action == .deleted{
            let appointment = AppointmentsViewController.macthEventWithAppointment(eventIdentifier: self.eventIdentifier)
            if let appointment = appointment{
                State.deleteAppointment(appointment, completionHandler: { result in
                    if result == true {
                        _ = self.navigationController?.popViewController(animated: true)
                    }
                })
            }
        }
    }
}
