//
//  ElectricTableViewController.swift
//  Em-call
//
//  Created by Alex Sh on 15.02.2022.
//
import Foundation
import UIKit

class ElectricTableViewController:UIViewController,UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate
{
    //@IBOutlet weak var addPhotoTopConstraint: NSLayoutConstraint!
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    var dataStorage:DataStorage? = nil
    var listImageGalery:[String] = Array()
    @IBOutlet weak var addPhotoTopConstraint: NSLayoutConstraint!
    var settingsLauncher:SettingsLauncher = SettingsLauncher()
    
    @IBOutlet weak var glidingView: GlidingCollection!
    fileprivate var collectionView: UICollectionView!
    
    @IBOutlet weak var descTextView: UITextView!
    var selRow:Int = 0
    let cellReuseIdentifier = "cell"
    var address = "Unknow address"
    var dateAndTime = "2022/02/23"
    var contact = "+1 123 112 11 22"
    var card = "**** **** **** 1234"
   // private var images = [UIImage(named: "plus")!]
   // private var images = [UIImage()]
    fileprivate var images: [UIImage?] = []
    var countData = 0
    var countPhotoElectric = 0
    
    @IBOutlet weak var tableView: UITableView!
    
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
     //   loadImages()
        settingsLauncher.delegate = self
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        tableView.rowHeight = 45
        tableView.delegate = self
        tableView.dataSource = self
        descTextView.delegate = self
        
        setup()
        glidingView.isHidden = true
       // addPhotoTopConstraint.constant = 78
        dataStorage = appDelegate?.dataStorage
       // countPhotoElectric = (dataStorage?.load())!  as Int     // images = dataStorage.Electrician_1
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        collectionView.reloadData()
        collectionView.collectionViewLayout.invalidateLayout()
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:UIColor(red: 0 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1.0)]
        navigationController?.title = "Electric"
        let item1 = setBarButtom(str: "akar-icons_arrow-left")
        self.navigationItem.setLeftBarButtonItems([item1], animated: true)

       let item2 = setBarButtom(str: "gg_close")
       self.navigationItem.setRightBarButtonItems([item2], animated: true)
       /* if dataStorage != nil {        countData = dataStorage!.load()
            if countData > 0 {                var ind = 0                for _ in images {
                    images.append(dataStorage?.listImageGalery.listElectricImageGalery[ind])
                    ind = ind + 1                }            }        }*/
        countPhotoElectric = (dataStorage?.load())!  as Int
        if countPhotoElectric > 0  {
            images = dataStorage?.getImageArray(flag:0) as! [UIImage?]
            if images.count > 0 {
            collectionView.reloadData()
            }
        }
      }
        
    func setBarButtom(str:String)->UIBarButtonItem {
        let btn1 = UIButton(type: .custom)
         btn1.setImage(UIImage(named: str), for: .normal)
         btn1.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
         btn1.addTarget(self, action: #selector(self.back), for: .touchUpInside)
         let item1 = UIBarButtonItem(customView: btn1)
        return item1
    }
    
    @objc
    func back() {
        let firstVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Logo")
      // navigationController?.popViewController( animated: true)
        navigationController?.pushViewController(firstVC, animated: true)
       // navigationController?.popToRootViewController(animated: true)
    }

    
    @IBAction func BookNowClick(_ sender: Any) {
  
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "BookingVK")
        let transition = CATransition()
        transition.duration = 0.99
        transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        transition.type = CATransitionType.fade  //растворяется
                // transition.type = CATransitionType.reveal  //moving right
        self.navigationController?.view.layer.add(transition, forKey: nil)
                //  _ = self.navigationController?.popToRootViewController(animated: false)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    
    @IBAction func pressAddPhoto(_ sender: Any) {
        guard let navVC = self.navigationController
        else { return }
        settingsLauncher.showSettings(navigVC: navVC,dispatcher:0)
        glidingView.isHidden = false
        addPhotoTopConstraint.constant = 102
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        descTextView.resignFirstResponder()
    }
        // MARK: - Table view data source

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:            return 1
        case 1:            return 1
        case 2:            return 1
        case 3:            return 1
        default:            return 1
        }  
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
       return 4
   }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        // Создаём константу, именна через неё мы будем обращаться к свойствам и изменять их
    let header = view as! UITableViewHeaderFooterView
        // Установить цвет текста в label
    header.textLabel?.textColor = .black
        // Установить цвет фона для секции
    header.tintColor = UIColor.white
        // Установить шрифт и размер шрифта для label
   // header.textLabel?.font = UIFont(name: "Helvetica-Regular", size: 15)
    }

    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    
        switch section {
         case 0:            return ("Work location")
         case 1:            return ("Date and Time")
         case 2:            return ("Your contacts")
         case 3:            return ("Payment")
         default:            return ("Work location")
         }    
     }
    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       // let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
        var cell:CustCellTableViewCell
        let section = indexPath.section
        switch section {
      case 0:
        cell = tableView.dequeueReusableCell(withIdentifier: "cust_cell") as! CustCellTableViewCell
        cell.custCell.text = address
      case 1:
         cell = tableView.dequeueReusableCell(withIdentifier: "cust_cell") as! CustCellTableViewCell
        cell.custCell.text = dateAndTime                 // cell.imageCell.isHidden = true
        cell.imageCell?.image = UIImage(named: "uil_calendar-alt")
      case 2:
         cell = tableView.dequeueReusableCell(withIdentifier: "cust_cell2") as! CustCellTableViewCell
        cell.custCell2?.text = contact
      case 3:
         cell = tableView.dequeueReusableCell(withIdentifier: "cust_cell") as! CustCellTableViewCell
        cell.custCell?.text = card
                cell.imageCell?.image = UIImage(named: "Vector")
      default:
        cell = tableView.dequeueReusableCell(withIdentifier: "cust_cell2") as! CustCellTableViewCell
       cell.custCell2?.text = contact
        }
         cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
        // cell.textLabel?.font = UIFont(name: "Roboto", size: 13)
          return cell
    }
    
    // method to run when table view cell is tapped
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         print("You tapped cell number \(indexPath.row).")
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let nameXibName = ["Map","Calendar"]
        let section = indexPath.section
        var vc:UIViewController
        switch section        //if indexPath.row == 0
        {
        case 0:                 vc = storyboard.instantiateViewController(withIdentifier: nameXibName[0])
                (vc as! MapViewController).delegate = self
            navigationController?.pushViewController(vc , animated: true)
            return
        case 1:                  vc = storyboard.instantiateViewController(withIdentifier: nameXibName[1])
             (vc as! CalendarViewController).delegate = self
            navigationController?.pushViewController(vc, animated: true)
            return
        case 2:             vc = storyboard.instantiateViewController(withIdentifier: nameXibName[1])
         (vc as! CalendarViewController).delegate = self
            navigationController?.pushViewController(vc, animated: true)
        case 3:             vc = storyboard.instantiateViewController(withIdentifier: nameXibName[1])
          (vc as! CalendarViewController).delegate = self
            navigationController?.pushViewController(vc, animated: true)
        default:            return
        }
     }
}

// MARK: - Setup
extension ElectricTableViewController {
  
  func setup() {
    setupGlidingCollectionView()
  }
  
  private func setupGlidingCollectionView() {
    glidingView.dataSource = self
    
    let nib = UINib(nibName: "CollectionCell", bundle: nil)
    collectionView = glidingView.collectionView
    collectionView.register(nib, forCellWithReuseIdentifier: "Cell")
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.backgroundColor = glidingView.backgroundColor
  }

}


extension ElectricTableViewController:MapViewControllerDelegate {
    func delegateClick(text:String) {
        address = text
                //   NotificationCenter.default.post(name: NSNotification.Name(rawValue: "delegateClick"), object: nil)
        tableView.reloadData()
    }
}
extension ElectricTableViewController:CalendarViewControllerDelegate {
    func calendarDelegateClick(text:String,flagData:Int) {
         switch flagData {
        case 0:            dateAndTime = text
        case 1:            contact = text
        case 2:            card = text
        default:            break
        }
        tableView.reloadData()
    }
}

extension ElectricTableViewController:SettingsLauncherDelegate {
    func settingsDelegateClick( img : UIImage?,selRow:Int, imgName :String?) {
        if img != nil {
            images.append(img!)
            
            collectionView.reloadData()
            if imgName != nil {
                listImageGalery.append(imgName!)
                dataStorage?.addListImageGalery(image: img!, imageName: imgName!, flagTypeGalery: 0)
            }
        }
        else {
            self.selRow = selRow
        }
    }
}
// MARK: - CollectionView 🎛
extension ElectricTableViewController: UICollectionViewDataSource, UICollectionViewDelegate {
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   // let section = glidingView.expandedItemIndex
    return images.count
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? CollectionCell else { return UICollectionViewCell() }
            ////let section = glidingView.expandedItemIndex
    if images.count>0 {
    let image = images[indexPath.row]
                // let image = images[0]
    cell.imageView.image = image
    }
    cell.contentView.clipsToBounds = true
    
    let layer = cell.layer
    let config = GlidingConfig.shared
    layer.shadowOffset = config.cardShadowOffset
    layer.shadowColor = config.cardShadowColor.cgColor
    layer.shadowOpacity = config.cardShadowOpacity
    layer.shadowRadius = config.cardShadowRadius
    
    layer.shouldRasterize = true
    layer.rasterizationScale = UIScreen.main.scale
    
    return cell
  }
  
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let section = glidingView.expandedItemIndex
    let item = indexPath.item
    print("Selected item #\(item) in section #\(section)")
  }
  
}
// MARK: - Gliding Collection 🎢
extension ElectricTableViewController: GlidingCollectionDatasource {
  
  func numberOfItems(in collection: GlidingCollection) -> Int {
   // return items.count
    return 0
  }
  
  func glidingCollection(_ collection: GlidingCollection, itemAtIndex index: Int) -> String {
   // return "– " + items[index]
    return "– "
  }
}
   
public extension UINavigationController {
    /**     Pop current view controller to previous view controller.
     - parameter type:     transition animation type.
     - parameter duration: transition animation duration.
     */
    func pop(transitionType type: CATransitionType = .fade, duration: CFTimeInterval = 0.3) {
      //  self.addTransition(transitionType: type, duration: duration)
        let transition = CATransition()
        transition.duration = 0.88
        transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        transition.type = CATransitionType.fade
        self.navigationController?.view.layer.add(transition, forKey: nil)
        self.popViewController(animated: false)
    }
    /**     Push a new view controller on the view controllers stack.
     - parameter vc:       view controller to push.
     - parameter type:     transition animation type.
     - parameter duration: transition animation duration.     */
    func push(viewController vc: UIViewController, transitionType type: CATransitionType = .fade, duration: CFTimeInterval = 0.3) {
     //   self.addTransition(transitionType: type, duration: duration)
        let transition = CATransition()
        transition.duration = 0.88
        transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        transition.type = CATransitionType.fade
        self.navigationController?.view.layer.add(transition, forKey: nil)
        self.pushViewController(vc, animated: false)
    }
}

