//
//  MainViewController.swift
//  DemoApp
//
//  Created by Smaato Inc on 20.04.18.
//  Copyright © 2018 Smaato Inc. All rights reserved.
//

import UIKit

class MainViewController: UITableViewController {

    private let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        clearsSelectionOnViewWillAppear = true
    }

    //MARK: - UITableViewDelegate and UITableViewDataSource

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UITableViewHeaderFooterView(frame: CGRect.zero)
    }

    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        guard let header = view as? UITableViewHeaderFooterView else {
            return
        }

        #if compiler(>=5.1)
        if #available(iOS 13.0, *) {
            header.contentView.backgroundColor = UIColor.systemGroupedBackground
        }
        #endif
        
        header.textLabel?.textColor = .appColor
        header.textLabel?.font = UIFont(appFont: .SFDisplay_Semibold, size: 24)
        header.textLabel?.text = Sections(rawValue: section)?.headerTitle()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return Sections.allCases.count;
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat(40.0)
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat(0.00001)
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch Sections(rawValue: section)! {
        case .UnifiedBidding:
            return 1
        case .Mediation:
            return NetworkType.allCases.count
        case .CSM:
            return NetworkType.allCases.count;
        case .Primary:
            return AdType.allCases.count
        case .Other:
            return OtherContent.allCases.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else {
            return UITableViewCell()
        }

        switch Sections(rawValue: indexPath.section)! {
        case .UnifiedBidding:
            cell.textLabel?.text = NetworkType.MoPub.identifier
            break
        case .Mediation:
            cell.textLabel?.text = NetworkType(rawValue: indexPath.row)?.identifier
            break
        case .CSM:
            cell.textLabel?.text = NetworkType(rawValue: indexPath.row)?.identifier
            break
        case .Primary:
            cell.textLabel?.text = AdType(rawValue: indexPath.row)?.identifier
            break
        case .Other:
            let otherCase = OtherContent(rawValue: indexPath.row)
            cell.textLabel?.text = otherCase?.identifier
            if (otherCase == .Splash) {
                cell.accessoryView = splashSwitch
            }
            break
        }

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        switch Sections(rawValue: indexPath.section)! {
        case .UnifiedBidding:
            showViewControllerForSection(section: .UnifiedBidding)
            break
        case .Mediation:
            showViewControllerForSection(section: .Mediation, networkType: NetworkType(rawValue: indexPath.row))
            break
        case .Primary:
            showViewControllerForSection(section: .Primary, adType: AdType(rawValue: indexPath.row))
            break
        case .CSM:
            showViewControllerForSection(section: .CSM, networkType: NetworkType(rawValue: indexPath.row))
            break
        case .Other:
            showViewControllerForSection(section: .Other, otherContent: OtherContent(rawValue: indexPath.row))
            break
        }
    }

    func showViewControllerForSection(section: Sections, adType: AdType? = nil, networkType: NetworkType? = nil, otherContent: OtherContent? = nil) {
        var presentedViewController: UIViewController?
        switch section {
        case .UnifiedBidding:
            presentedViewController = self.ubViewController()
            break
        case .Mediation:
            presentedViewController = self.viewControllerFor(networkType: networkType!, adSection: section)
            break
        case .Primary:
            presentedViewController = self.viewControllerFor(adType: adType!)
            break
        case .CSM:
            presentedViewController = self.viewControllerFor(networkType: networkType!, adSection: section)
            break
        case .Other:
            showViewControllerFor(otherContent: otherContent!)
            return
        }

        guard let viewController = presentedViewController else {
            return
        }

        navigationController?.pushViewController(viewController, animated: true)
    }

    func ubViewController() -> UnifiedBiddingViewController? {
        let storyboard = UIStoryboard(name: Sections.UnifiedBidding.identifier, bundle: nil)
        guard let viewController = storyboard.instantiateInitialViewController() as? UnifiedBiddingViewController else {
            return nil
        }
        return viewController
    }

    func viewControllerFor(adType: AdType) -> AdTypesViewController? {
        let storyboard = UIStoryboard(name: Sections.Primary.identifier, bundle: nil)
        guard let viewController = storyboard.instantiateInitialViewController() as? AdTypesViewController else {
            return nil
        }
        viewController.adtype = adType
        viewController.presenter = PresenterBuilder.buildPresenterFor(adType: adType)
        return viewController
    }
    
    func viewControllerFor(networkType: NetworkType, adSection: Sections) -> MediationAdTypesViewController? {
        let storyboard = UIStoryboard(name: Sections.Mediation.identifier, bundle: nil)
        guard let viewController = storyboard.instantiateInitialViewController() as? MediationAdTypesViewController else {
            return nil
        }
        viewController.adSection = adSection
        viewController.networkType = networkType
        return viewController
    }

    func showViewControllerFor(otherContent: OtherContent) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        switch otherContent {
        case .Settings:
            guard let viewController = storyboard.instantiateViewController(withIdentifier: "SettingsViewController") as? SettingsViewController else {
                return
            }
            splitViewController?.showDetailViewController(viewController, sender: self)
        case .GDPR:
            guard let viewController = storyboard.instantiateViewController(withIdentifier: "GDPRSettingsViewController") as? GDPRSettingsViewController else {
                return
            }
            splitViewController?.showDetailViewController(viewController, sender: self)
        case .Splash:
            return
        }
    }
    
    var splashSwitch: UISwitch = {
        let aSwitch = UISwitch()
        if let splashAdValue = UserDefaults.standard.value(forKey: Constants.splashAdKey) as? String {
            aSwitch.isOn = splashAdValue == "0" ? false : true
        }
        aSwitch.addTarget(self, action: #selector(splashSwitchChanged), for: .valueChanged)
        return aSwitch
    }()
    
    @objc
    func splashSwitchChanged(splashAdSwitch: UISwitch) {
        UserDefaults.standard.setValue(splashAdSwitch.isOn ? "1" : "0", forKey: Constants.splashAdKey)
        if (splashAdSwitch.isOn) {
            let alertController = UIAlertController(title: "Info", message: "Splash ad will be presented on every app launch from now on", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "Okay", style: .default, handler: { (action) in
                alertController.dismiss(animated: true)
            }))
            present(alertController, animated: true)
        }
    }

}
