//
/*
 * Copyright (c) 2021 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import UIKit

protocol RoomRollsAndRightsPickerViewControllerDelegate: AnyObject {
    func powerLevelsDidChange(controller: RoomRollsAndRightsPickerViewController, viewState: RoomRollsAndRightsViewState)
}

final class RoomRollsAndRightsPickerViewController: UITableViewController {

    enum SelectedViewStateProperty {
        case general
        case send
        case invite
        case redact
        case ban
    }
    
    var viewState: RoomRollsAndRightsViewState?
    var selectedViewStateProperty: SelectedViewStateProperty?
    
    var theme: Theme!
    weak var delegate: RoomRollsAndRightsPickerViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        registerThemeServiceDidChangeThemeNotification()
        update(theme: theme)

        self.tableView.dataSource = self
        self.tableView.delegate = self
    }
    
    private func powerLevel(for viewStateProperty: SelectedViewStateProperty?) -> RoomPowerLevel? {
        guard let viewStateProperty = viewStateProperty, let viewState = viewState else {
            return nil
        }
        
        switch viewStateProperty {
        case .general:
            return powerLevel(for: viewState.powerLevelGeneral)
        case .send:
            return powerLevel(for: viewState.powerLevelSend)
        case .redact:
            return powerLevel(for: viewState.powerLevelRedact)
        case .invite:
            return powerLevel(for: viewState.powerLevelInvite)
        case .ban:
            return powerLevel(for: viewState.powerLevelBan)
        }
    }
    
    func powerLevel(for value: Int) -> RoomPowerLevel {
        if value >= RoomPowerLevel.admin.rawValue {
            return RoomPowerLevel.admin
        }
        else if value >= RoomPowerLevel.moderator.rawValue {
            return RoomPowerLevel.moderator
        }
        else {
            return RoomPowerLevel.user
        }
    }
    
    // MARK: - Theme
    
    private func update(theme: Theme) {
        self.theme = theme
        
        view.backgroundColor = theme.headerBackgroundColor
        self.tableView.backgroundColor = theme.headerBackgroundColor
        
        if let navigationBar = navigationController?.navigationBar {
            theme.applyStyle(onNavigationBar: navigationBar)
        }
        self.tableView.reloadData()
    }

    private func registerThemeServiceDidChangeThemeNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
    }
    
    @objc private func themeDidChange() {
        update(theme: ThemeService.shared().theme)
    }

}

// MARK: - UITableViewDataSource

extension RoomRollsAndRightsPickerViewController {
    
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView()
        footerView.backgroundColor = theme.headerBackgroundColor
        return footerView
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "rolls_and_rights_picker_cells")
        cell.tintColor = ThemeService.shared().theme.tintColor   // only for the accessory view
        cell.backgroundColor = theme.backgroundColor
        cell.textLabel?.textColor = BWIBuildSettings.shared.useNewBumColors ? theme.tintColor : theme.textPrimaryColor

        let powerLevel = self.powerLevel(for: selectedViewStateProperty)
        
        switch indexPath.row {
        case 0:
            cell.textLabel?.text = BWIL10n.bwiRollsAndRightsAdmin
            cell.accessoryType = powerLevel == .admin ? .checkmark : .none
        case 1:
            cell.textLabel?.text = BWIL10n.bwiRollsAndRightsModerator
            cell.accessoryType = powerLevel == .moderator ? .checkmark : .none
        case 2:
            cell.textLabel?.text = BWIL10n.bwiRollsAndRightsUser
            cell.accessoryType = powerLevel == .user ? .checkmark : .none
        default:
            assertionFailure("invalid indexPath in RollsAndRightsPickerViewController tableview")
        }
        return cell
    }

}

// MARK: - UITableViewDelegate

extension RoomRollsAndRightsPickerViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var newPowerLevel: Int?
        switch indexPath.row {
        case 0:
            newPowerLevel = RoomPowerLevel.admin.rawValue
        case 1:
            newPowerLevel = RoomPowerLevel.moderator.rawValue
        case 2:
            newPowerLevel = RoomPowerLevel.user.rawValue
        default:
            break
        }
        
        if let newPowerLevel = newPowerLevel, let selectedViewStateProperty = selectedViewStateProperty {
            switch selectedViewStateProperty {
            case .general:
                viewState?.powerLevelGeneral = newPowerLevel
            case .send:
                viewState?.powerLevelSend = newPowerLevel
            case .redact:
                viewState?.powerLevelRedact = newPowerLevel
            case .invite:
                viewState?.powerLevelInvite = newPowerLevel
            case .ban:
                viewState?.powerLevelBan = newPowerLevel
            }
            
            if let viewState = viewState {
                self.delegate?.powerLevelsDidChange(controller: self, viewState: viewState)
            }
        }

        self.navigationController?.popViewController(animated: true)
    }
}

