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

import UIKit

class NewUnifiedBiddingAdViewController: UITableViewController {

    private let newMoPubPresenter = NewHBMoPubBannerPresenter()

    var presenter: HeaderBiddingPresenter!

    @IBOutlet private weak var adSpaceIdTextFiled: InsetTextFiled!
    @IBOutlet private weak var nameTextFiled: InsetTextFiled!
    @IBOutlet private weak var sizeLable: UILabel!
    @IBOutlet private weak var sizeArrowImageView: UIImageView!
    @IBOutlet private weak var adTypeLabel: UILabel!
    @IBOutlet weak var adTypeArrowImageView: UIImageView!
    @IBOutlet weak var sizeCell: UITableViewCell!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "New ad"

        func placeholderAttributedString(text: String) -> NSAttributedString {
            return NSAttributedString(string: text,
                    attributes: [NSAttributedString.Key.foregroundColor: UIColor.appGrayText,
                                 NSAttributedString.Key.font: UIFont(appFont: .SFText_Regular, size: 14)!])
        }

        adSpaceIdTextFiled.attributedPlaceholder = placeholderAttributedString(text: "Ad space Id")
        nameTextFiled.attributedPlaceholder = placeholderAttributedString(text: "Name")

        sizeLable.textColor = UIColor.appGrayText
        sizeLable.font = UIFont(appFont: .SFText_Regular, size: 14)!

        let closeKeyboard = UITapGestureRecognizer(target: self, action: #selector(NewUnifiedBiddingAdViewController.viewTapped(_:)))
        closeKeyboard.delegate = self
        view.addGestureRecognizer(closeKeyboard)
    }

    private func adModels() -> [MediationAdModel] {
        return presenter.mopubModels as [MediationAdModel]
    }

    //MARK: Actions

    @IBAction func onCancel(_ sender: Any) {
        dismiss(animated: true)
    }

    @IBAction func onSave(_ sender: Any) {
        adSpaceIdTextFiled.resignFirstResponder()
        nameTextFiled.resignFirstResponder()
        saveMoPubNewAd()
    }

    func saveMoPubNewAd() {
        if newMoPubPresenter.adType == .Banner {
            guard let adSpaceId = newMoPubPresenter.adSpaceId,
                  let name = newMoPubPresenter.name,
                  let adType = newMoPubPresenter.adType,
                  let size = newMoPubPresenter.size else {
                return
            }
            presenter.add(mopubAdModel: adSpaceId, name: name, adType: adType, size: size)
        } else {
            guard let adSpaceId = newMoPubPresenter.adSpaceId,
                  let name = newMoPubPresenter.name,
                  let adType = newMoPubPresenter.adType else {
                return
            }
            presenter.add(mopubAdModel: adSpaceId, name: name, adType: adType)
        }
        dismiss(animated: true)
    }

    //MARK: Private

    private func showSizeSelector() {
        showActionScheet(with: "SELECT BANNER SIZE", actions: mopubSizeActions(), fromView: sizeArrowImageView)
    }

    private func mopubSizeActions() -> [UIAlertAction] {
        let actions: [UIAlertAction] = MoPubBannerSizes.allCases.map { (size) -> UIAlertAction in
            let action: UIAlertAction = UIAlertAction(title: size.description, style: .default) { [weak self] action -> Void in
                self?.newMoPubPresenter.size = size
                self?.sizeLable.text = size.description
            }
            return action
        }
        return actions
    }

    private func showAdTypeSelector() {
        let actions: [UIAlertAction] = AdType.allCases.map { (adType) -> UIAlertAction in
            let action: UIAlertAction = UIAlertAction(title: adType.identifier, style: .default) { [weak self] action -> Void in
                self?.newMoPubPresenter.adType = adType

                if adType == AdType.Banner {
                    self?.sizeCell.isHidden = false;
                } else {
                    self?.sizeCell.isHidden = true;
                }

                self?.adTypeLabel.text = adType.identifier
            }
            return action
        }

        showActionScheet(with: "SELECT Ad type", actions: actions, fromView: adTypeArrowImageView)
    }

    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) {
        adSpaceIdTextFiled.resignFirstResponder()
        nameTextFiled.resignFirstResponder()
    }

    //MARK: UITableViewControllerDelegate

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch (indexPath.section, indexPath.row) {
        case (2, 0):
            showAdTypeSelector()
            break
        case (3, 0):
            showSizeSelector()
            break
        default:
            return
        }
    }
}

extension NewUnifiedBiddingAdViewController: UIGestureRecognizerDelegate {

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

        return true
    }
}

extension NewUnifiedBiddingAdViewController: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case adSpaceIdTextFiled:
            newMoPubPresenter.adSpaceId = textField.text
        case nameTextFiled:
            newMoPubPresenter.name = textField.text
        default:
            break
        }
    }

    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        return false
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return true
    }
}

class NewHBMoPubBannerPresenter {
    var adSpaceId: String?
    var adType: AdType?
    var name: String?
    var size: MoPubBannerSizes?
}


