//
//  SettingsLauncher.swift
//  youtube
//
//  Created by Alex Sh


import UIKit

class Setting: NSObject {
    let name: String
    let imageName: String
    
    init(name: String, imageName: String) {
        self.name = name
        self.imageName = imageName
    }
}

protocol SettingsLauncherDelegate:class {
    func settingsDelegateClick(img: UIImage?,selRow:Int)
}

class SettingsLauncher : UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    let imagePickerController = UIImagePickerController()
    var imgs: [UIImage]? = nil
    let blackView = UIView()
    let textLocation:UITextField = UITextField()
    let whatDoYou:UITextField = UITextField()
    let micro = UIImageView()
    let doIt:UIButton = UIButton()
    let back = UIView()
    
    weak var delegate:SettingsLauncherDelegate?
    var dispatcher:Int = 0
      var tableView = UITableView()
      var navController:UINavigationController? = nil
    let frazes:[String] = ["Select source", "Camera", "Photogalery","Cancel",
                           "Electrician Emergency Departure",
                           "Entering electricity into the house",
                           "Dismantling the electric heated towel rail",
                           "Dismantling the electric meter"]
      let cellId = "cellId"
      let cellHeight: CGFloat = 50
      var imgArray:[UIImage]? = []
 
      
    func showSettings(navigVC:UINavigationController,dispatcher:Int) {
    // func showSettings(navigVC:UINavigationController) {
          //show menu
        tableView.delegate = self
        tableView.dataSource = self
       tableView.delegate = self
        imagePickerController.delegate = self
        imagePickerController.allowsEditing = true
       tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        navController = navigVC
        self.dispatcher = dispatcher
        if dispatcher == 0 {
        selectPhoto()
        }
        else {
            selectWork()
        }
      }
    
    func selectPhoto() {
        if let window = UIApplication.shared.keyWindow {
        blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
          blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
         window.addSubview(blackView)
        self.tableView.layer.cornerRadius = 10
        window.addSubview(tableView)
         // let height: CGFloat = CGFloat(settings.count) * cellHeight
      let height: CGFloat = 200
        let yw = window.frame.height - height
       tableView.frame = CGRect(x: 10, y: window.frame.height, width: window.frame.width-10, height: height)
           blackView.frame = window.frame
        blackView.alpha = 0
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
               self.blackView.alpha = 1
            self.tableView.frame = CGRect(x:10, y: yw, width: self.tableView.frame.width-10, height: self.tableView.frame.height)
          self.tableView.layer.cornerRadius = 10
         }, completion: nil)
    }
    }
    
    func selectWork() {
        if let window = UIApplication.shared.keyWindow {
        blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
          blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
         window.addSubview(blackView)
        self.back.layer.cornerRadius = 10
       // self.tableView.layer.cornerRadius = 10
      //  window.addSubview(tableView)
        window.addSubview(back)
            let height: CGFloat = 370.0
             back.frame = CGRect(x: 10, y: window.frame.height-160.0, width: window.frame.width-10, height: height)
            back.translatesAutoresizingMaskIntoConstraints = false
            back.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
            back.widthAnchor.constraint(equalToConstant: (window.frame.width-10)).isActive = true
            var margins = window.layoutMarginsGuide
           // back.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20).isActive = true
           // back.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 20).isActive = true
            //topAnchor
            back.topAnchor.constraint(equalTo: margins.topAnchor, constant: (window.frame.height -  85)).isActive = true
           // back.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 20).isActive = true
           // back.widthAnchor.constraint(equalToConstant:(window.frame.width-10)).isActive = true
            back.heightAnchor.constraint(equalToConstant: height).isActive = true
        let yw = window.frame.height - height - 120
          //  let yw = window.frame.height - height - 85
          //  back.frame = CGRect(x: 10, y: window.frame.height-160.0, width: window.frame.width-10, height: height)
              //  blackView.frame = window.frame
            back.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
                        // let height: CGFloat = CGFloat(settings.count) * cellHeight
                        //let height: CGFloat = 200
                        // let yw = window.frame.height - height - 160
                        //  tableView.frame = CGRect(x: 10, y: window.frame.height-160, width: window.frame.width-10, height: height)
          /*  textLocation.frame = CGRect(x: 20, y: window.frame.height-150.0, width: window.frame.width-60, height: 55)*/
            back.addSubview(textLocation)
            textLocation.translatesAutoresizingMaskIntoConstraints = false
            textLocation.centerXAnchor.constraint(equalTo: back.centerXAnchor).isActive = true
            textLocation.widthAnchor.constraint(equalToConstant: (window.frame.width-60)).isActive = true
            var margin = back.layoutMarginsGuide
            textLocation.topAnchor.constraint(equalTo: margin.topAnchor, constant: (window.frame.height - height - 85)).isActive = true
            textLocation.heightAnchor.constraint(equalToConstant: 55).isActive = true
            textLocation.text = "Unknow address"
           // textLocation.backgroundColor = UIColor(white: 0, alpha: 1.0)
          //  textLocation.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5,  alpha: 1.0)
           // textLocation.textColor = UIColor(red: 0.5, green: 0.5, blue: 0.5,  alpha: 1.0)
  
            tableView.frame = CGRect(x: 10, y: window.frame.height-240.0, width: window.frame.width-10, height: height - 200)
          //  back.addSubview(tableView)
 
        blackView.frame = window.frame
        blackView.alpha = 0
                                        //ANIMATION
            UIView.animate(withDuration: 0.7, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
               self.blackView.alpha = 1
           // self.tableView.frame = CGRect(x:10, y: yw, width:
            //self.tableView.frame.width-10, height: self.tableView.frame.height)
          //  self.back.frame = CGRect(x:10, y: yw, width:
          //  self.back.frame.width-10, height: self.back.frame.height)
            self.back.translatesAutoresizingMaskIntoConstraints = false
            self.back.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
            self.back.widthAnchor.constraint(equalToConstant: (window.frame.width-20)).isActive = true
             margins = window.layoutMarginsGuide
            self.back.topAnchor.constraint(equalTo: margins.topAnchor, constant: yw).isActive = true
            self.back.heightAnchor.constraint(equalToConstant: self.back.frame.height).isActive = true
               // window.addSubview(self.back)
           // self.textLocation.frame = CGRect(x: 20, y: yw - 425, width: window.frame.width-60, height: self.textLocation.frame.height)
            
            self.textLocation.translatesAutoresizingMaskIntoConstraints = false
            self.textLocation.centerXAnchor.constraint(equalTo: self.back.centerXAnchor).isActive = true
            self.textLocation.widthAnchor.constraint(equalToConstant: (window.frame.width-60)).isActive = true
            margin = self.back.layoutMarginsGuide
            self.textLocation.topAnchor.constraint(equalTo: margin.topAnchor, constant: 10).isActive = true
            self.textLocation.heightAnchor.constraint(equalToConstant: 55).isActive = true
            
             self.tableView.frame = CGRect(x:10, y: yw - 300, width:
             self.tableView.frame.width-20, height: self.tableView.frame.height)
          self.tableView.layer.cornerRadius = 10
            self.back.layer.cornerRadius = 10
         }, completion: nil)
    }
    }
      
      @objc func handleDismiss() {
          UIView.animate(withDuration: 0.5) {
              self.blackView.alpha = 0
            if self.dispatcher == 0 {
              if let window = UIApplication.shared.keyWindow {
                  self.tableView.frame = CGRect(x: 10, y: window.frame.height, width: self.tableView.frame.width-10, height: self.tableView.frame.height)
              }
            } else {
                if let window = UIApplication.shared.keyWindow {
                    self.back.frame = CGRect(x: 10, y: window.frame.height, width: self.back.frame.width-10, height: self.back.frame.height)
                    self.textLocation.frame = CGRect(x: 20, y:window.frame.height+10, width: window.frame.width-20, height: 55)
                    self.tableView.frame = CGRect(x: 10, y: window.frame.height, width: self.tableView.frame.width-10, height: self.tableView.frame.height)
                }
            }
          }
      }
    //The delegate UIImagePickerController
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[.editedImage] as? UIImage
        else {
            return }
 
        self.delegate?.settingsDelegateClick(img: image,selRow: 0)
        self.navController?.dismiss(animated: true)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
       // self.navController?.popViewController(animated: true)
        self.navController?.dismiss(animated: true, completion: nil)
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       // return trackList.count
        return 4
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
       return 1
   }// Default is 1 if not implemented
   
     
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let row = indexPath.row
        if dispatcher == 0 {
        cell.textLabel?.text = frazes[row]
        } else {
            cell.textLabel?.text = frazes[row+4]
        }
       /* switch row {
        case 0:
            cell.textLabel?.text = frazes[row]
        case 1:            cell.textLabel?.text = "Camera"
        case 2:            cell.textLabel?.text = "Photogalery"
        case 3:            cell.textLabel?.text = "Cancel"
        default:           break
        }*/
           // cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
       // cell.text.textAlignment = .center
        cell.textLabel?.textAlignment = .center

        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      /* let storyboard = UIStoryboard(name: "Main", bundle: nil)
        var vc:UIViewController
        vc = storyboard.instantiateViewController(withIdentifier: "DataProfile")
        (vc as! DataProfileViewController).delegate = self
      */
       let row = indexPath.row
        self.delegate?.settingsDelegateClick(img:nil,selRow: row)
       // navigationController?.pushViewController(vc, animated: true)
        if dispatcher == 0 {
      switch row        //if indexPath.row == 0
       {
        case 0:
         //  navigationController?.pushViewController(vc, animated: true)
           return
       case 1:
        self.imagePickerController.sourceType = .camera // options: .Camera , .PhotoLibrary , .SavedPhotosAlbum
        self.navController?.present(self.imagePickerController, animated: true, completion: nil)
       case 2:
        self.imagePickerController.sourceType = .savedPhotosAlbum
        self.navController?.present(self.imagePickerController, animated: true, completion: nil)
       // self.navController?.pushViewController(self.imagePickerController, animated: true)
       case 3:
        handleDismiss()
        return
       default:            return
       }
        }
        else {
            handleDismiss()
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
              var vc:UIViewController
              vc = storyboard.instantiateViewController(withIdentifier: "Electric")
            //  (vc as! ElectricTableViewController).delegate = self
            navController?.pushViewController(vc, animated: true)
        }
    }
  
    
  }

