//
//  NewAdSceneViewController.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 03/03/2019.
//  Copyright © 2019 Smaato Inc. All rights reserved.
//

import Foundation
import UIKit

class NewAdSceneViewController: UITableViewController {

    private let newPresenter = NewPresenter()

    var presenter: AdPresenting?
    var adType: AdType!
    
    @IBOutlet weak var sizeArrowImageView: UIImageView!
    @IBOutlet private weak var publisherIdTextFiled: InsetTextFiled!
    @IBOutlet private weak var nameTextFiled: InsetTextFiled!
    @IBOutlet weak var sizeLabel: UILabel!
    @IBOutlet weak var sizeCell: UITableViewCell!
    
    @IBOutlet weak var adSpaceIdDTextField: InsetTextFiled!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        func placeholderAttributedString(text: String) -> NSAttributedString {
            return NSAttributedString(string:text,
                                      attributes:[NSAttributedString.Key.foregroundColor: UIColor.appGrayText,
                                                  NSAttributedString.Key.font: UIFont(appFont: .SFText_Regular, size: 14)!])
        }
        
        adSpaceIdDTextField.attributedPlaceholder = placeholderAttributedString(text:"Ad space Id")
        publisherIdTextFiled.attributedPlaceholder = placeholderAttributedString(text:"Publisher ID")
        nameTextFiled.attributedPlaceholder = placeholderAttributedString(text:"Name")
        
        showSizeIfNeeded()
        
        let closeKeyboard = UITapGestureRecognizer(target: self, action: #selector(NewAdSceneViewController.viewTapped(_:)))
        closeKeyboard.delegate = self
        view.addGestureRecognizer(closeKeyboard)
    }
    
    @IBAction func onCancel(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func onSave(_ sender: Any) {
        adSpaceIdDTextField.resignFirstResponder()
        publisherIdTextFiled.resignFirstResponder()
        nameTextFiled.resignFirstResponder()
        
        if adType == AdType.Banner {
            saveBannerAd()
        } else {
            saveAd()
        }
    }
    
    //MARK: UITableViewControllerDelegate
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch (indexPath.section, indexPath.row) {
        case (3, 0):
            showSizeSelector()
            break
        default:
            return
        }
    }
    
    //MARK: Private
    
    private func showSizeIfNeeded() {
        if adType == AdType.Banner {
            sizeCell.isHidden = false;
        } else {
            sizeCell.isHidden = true;
        }
    }
    
    private func saveBannerAd() {
        guard let adSpaceId = newPresenter.adSpaceId,
            let publisherId = newPresenter.publisherId,
            let name = newPresenter.name,
            let size = newPresenter.size else {
                return
        }
        
        presenter?.add(adModel: publisherId, adSpaceId: adSpaceId, name: name, size: size)
        dismiss(animated: true)
    }
    
    private func saveAd() {
        guard let adSpaceId = newPresenter.adSpaceId,
            let publisherId = newPresenter.publisherId,
            let name = newPresenter.name else {
                return
        }
        
        presenter?.add(adModel: publisherId, adSpaceId: adSpaceId, name: name)
        dismiss(animated: true)
    }
    
    private func showSizeSelector() {
    
        let actions: [UIAlertAction] = BannerSize.allCases.map { (size) -> UIAlertAction in
            let action: UIAlertAction = UIAlertAction(title: size.description, style: .default) { [weak self] action -> Void in
                self?.newPresenter.size = size
                self?.sizeLabel.text = size.description
            }
            return action
        }
        
        showActionScheet(with: "SELECT BANNER SIZE", actions: actions, fromView: sizeArrowImageView)
    }
    
    
    private func showActionScheet(with title:String, actions:[UIAlertAction], fromView:UIView) {
        let actionSheetController: UIAlertController = UIAlertController(title: title,
                                                                         message: nil,
                                                                         preferredStyle: .actionSheet)
        
        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel)
        actionSheetController.addAction(cancelAction)
        
        actions.forEach {actionSheetController.addAction($0)}
        
        if let popoverController = actionSheetController.popoverPresentationController {
            popoverController.sourceView = fromView
            popoverController.sourceRect = CGRect(x: fromView.bounds.minX,
                                                  y: fromView.bounds.midY,
                                                  width: 0,
                                                  height: 0)
        }
        
        self.present(actionSheetController,
                     animated: true,
                     completion: nil)
    }
    
    @objc private func viewTapped(_ sender: UITapGestureRecognizer) {
        adSpaceIdDTextField.resignFirstResponder()
        publisherIdTextFiled.resignFirstResponder()
        nameTextFiled.resignFirstResponder()
    }
    
}

extension NewAdSceneViewController: UIGestureRecognizerDelegate {
    
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if (touch.view?.isDescendant(of: nameTextFiled))! {
            return false
        } else if (touch.view?.isDescendant(of: adSpaceIdDTextField))! {
            return false
        } else if (touch.view?.isDescendant(of: publisherIdTextFiled))! {
            return false
        } else if (touch.view?.isDescendant(of: tableView.cellForRow(at: IndexPath(item: 0, section: 3))!))! {
            return false
        }
        
        return true
    }
}

extension NewAdSceneViewController: UITextFieldDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case adSpaceIdDTextField:
            newPresenter.adSpaceId = textField.text
        case publisherIdTextFiled:
            newPresenter.publisherId = textField.text
        case nameTextFiled:
            newPresenter.name = textField.text
        default:
            break
        }
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        return false
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return true
    }
}

class NewPresenter {
    var adSpaceId: String?
    var publisherId: String?
    var name: String?
    var size: BannerSize?
}
