//
//  ClinicalStatusViewController.swift
//  iPOS
//
//  Created by BBC on 13/10/16.
//  Copyright © 2016 BBC. All rights reserved.
//

import UIKit

protocol ClinicalStatusViewContollerDelegate {
    func selectedClinicalStatus(clinicalStatus: ClinicalStatus)
}

class ClinicalStatusViewContoller: UITableViewController{
    var isSlideMenuEnabled = true
    var loadRecentClinicalStatus = true
    var lastRequestReturnData = true
    var isAddNewCSEnable = false
    var contact: Contact?
    var addCSButton = UIButton()
    var delegate: ClinicalStatusViewContollerDelegate?
    var prescriptionType: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if (self.isSlideMenuEnabled){
            self.setNavigationBarItem()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if self.isAddNewCSEnable{
            self.createButton()
        }
    
        self.LoadClinicalStatus(contactId: self.contact?.ContactId, prescriptionType: prescriptionType, top: 100, skip: 0)
    }
    
    func createButton(){
        self.addCSButton = UIButton(type: .custom)
        self.addCSButton.setImage(UIImage.init(named: "add.png"), for: .normal)
        self.addCSButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        self.addCSButton.addTarget(self, action: #selector(insertNewObject), for: .touchUpInside)
        let addButtonBarItem = UIBarButtonItem(customView: addCSButton)
        self.navigationItem.rightBarButtonItem = addButtonBarItem
    }
    
    @objc func insertNewObject(){
        if(self.contact == nil) {
            return
        }
        self.openPrescriptionTypeSelector()
    }
    
    func openPrescriptionTypeSelector(){
        let optionMenu = UIAlertController(title: Util.getString("Prescription type"), message: nil, preferredStyle: UIAlertController.Style.actionSheet)
        
        let glassesAction = UIAlertAction(title: Util.getString("Glasses"), style: .default, handler : { (action) -> Void in
            self.selectedPrescriptionType(prescriptionType: "GL")
        })
        glassesAction.setValue(UIImage.init(named: "glasses50.png"), forKey: "image")
        
        let contactLensAction = UIAlertAction(title: Util.getString("Contact Lens"), style: .default, handler : { (action) -> Void in
            self.selectedPrescriptionType(prescriptionType: "CL")
        })
        contactLensAction.setValue(UIImage.init(named: "eye50.png"), forKey: "image")
        
        let cancel = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
        
        optionMenu.addAction(glassesAction)
        optionMenu.addAction(contactLensAction)
        optionMenu.addAction(cancel)
        
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad )
        {
            if let currentPopoverpresentioncontroller = optionMenu.popoverPresentationController{
                currentPopoverpresentioncontroller.sourceView = addCSButton
                currentPopoverpresentioncontroller.sourceRect = addCSButton.bounds
                currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.up;
                self.present(optionMenu, animated: true, completion: nil)
            }
        }else{
            self.present(optionMenu, animated: true, completion: nil)
        }
    }
    
    func selectedPrescriptionType(prescriptionType: String){
        let clinicalStatusDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "clinicalStatus") as! ClinicalStatusDetailViewController
        let cs = ClinicalStatus()
        cs.ContactId = contact!.ContactId
        cs.Contact = contact
        clinicalStatusDetailViewController.isNew = true
        clinicalStatusDetailViewController.clinicalStatus = cs
        clinicalStatusDetailViewController.contact = contact!
        clinicalStatusDetailViewController.clinicalStatus.PrescriptionType = prescriptionType
        self.navigationController?.pushViewController(clinicalStatusDetailViewController, animated: true)
    }

    
    func LoadClinicalStatus(contactId: String?, prescriptionType: String?, top: Int, skip: Int){
        State.LoadClinicalStatus(contactId, prescriptionType: prescriptionType, top: top, skip: skip, completionHandler: { result in
            if(result == nil){
                NetworkController.AlertConnectionError(viewController: self)
            }
            else{
                self.lastRequestReturnData = result!
                self.tableView.reloadData()
            }
        })
    }
    
    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.
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.clinicalStatus.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellHistory") as! ClinicalStatusCustomCell
        
        let clinicalStatus = State.clinicalStatus[indexPath.row]
        
        if(clinicalStatus.PrescriptionType == "GL"){
            cell.clinicalStatusTypeImage.image = UIImage(named: "glasses.png")
        }
        else{
            cell.clinicalStatusTypeImage.image = UIImage(named: "lens.png")
        }
        
        cell.tfTitle.text = "\(clinicalStatus.getPrescriptionsType()) - \(clinicalStatus.getDistanceType())"
        
        if !(clinicalStatus.Contact?.IsLegalPerson!)!{
            cell.tfSubtitle.text = clinicalStatus.Contact!.getFullNameSexAge()
        }
        else{
            cell.tfSubtitle.text = "\(clinicalStatus.Contact!.LastName)"
        }
        
        cell.lfDate.text = "\(Util.DateToShortDateString(date: clinicalStatus.CreateTime))"
        
        cell.lfDetail.text = clinicalStatus.getRX()
        
        if (indexPath.row == State.clinicalStatus.count-1 && State.clinicalStatus.count > 99 && self.lastRequestReturnData){
            self.LoadClinicalStatus(contactId: nil, prescriptionType: prescriptionType, top: 20, skip: State.clinicalStatus.count)
        }

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let clinicalStatus = State.clinicalStatus[indexPath.row]
        
        if let _delegate = delegate{
            _delegate.selectedClinicalStatus(clinicalStatus: clinicalStatus)
        }
        else{
            let detailViewController = self.storyboard?.instantiateViewController(withIdentifier: "clinicalStatus") as! ClinicalStatusDetailViewController
            detailViewController.clinicalStatus = clinicalStatus
            detailViewController.isNew = false
            self.navigationController?.pushViewController(detailViewController, animated: true)
        }
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
}
extension ClinicalStatusViewContoller : SlideMenuControllerDelegate {
    
    func leftWillOpen() {
    }
    
    func leftDidOpen() {
    }
    
    func leftWillClose() {
    }
    
    func leftDidClose() {
    }
    
    func rightWillOpen() {
    }
    
    func rightDidOpen() {
    }
    
    func rightWillClose() {
    }
    
    func rightDidClose() {
    }
}
