//
//  CenterViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/3/27.
//

import UIKit
///个人中心
class MPSideA_CenterViewController: MPSideA_BaseViewController {
    @IBOutlet weak var tableView: UITableView!{
        didSet{
            if #available(iOS 15.0, *) {
                tableView.sectionHeaderTopPadding = 0
            }
            tableView.estimatedRowHeight = 200
            tableView.rowHeight = UITableView.automaticDimension
            //扩充tableView滚动范围
            tableView.contentInset = .init(top: 27*width, left: 0, bottom: 100*width, right: 0)
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(UINib(nibName: CenterTableViewCellID, bundle: nil), forCellReuseIdentifier: CenterTableViewCellID)
        }
    }
    @IBOutlet weak var noticeView: UIView!
    private let CenterTableViewCellID = "MPSideA_CenterTableViewCell"
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .init(hex: "#000000")
        //触发音乐缺失闭包
        nullMusicAction = {
            [weak self] in
            //刷新页面
            self?.reload()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(successfullCreateAction), notificationName: .sideA_creat_music)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(fileMissAction(_ :)), notificationName: .sideA_null_music)
        reload()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        NotificationCenter.default.removeObserver(self)
    }
    //刷新数据源
    private func reload() {
        MPSideA_LoadDataMusic.shared.reloadListData()
        //检索用户上传音乐是否为空
        if MPSideA_LoadDataMusic.shared.userlistMusics.count == 0 {
            //展示提醒框
            noticeView.isHidden = false
        }else {
            noticeView.isHidden = true
        }
        tableView.showMessage(MPSideA_LoadDataMusic.shared.userlistMusics.count)
        tableView.reloadData()
    }
    //收到音乐库更新通知
    @objc private func successfullCreateAction() {
        DispatchQueue.main.async {
            [weak self] in
            self?.reload()
        }
    }
    //前往设置页
    @IBAction func setActionClick(_ sender: UIButton) {
        let setVC = MPSideA_SettingViewController()
        navigationController?.pushViewController(setVC, animated: true)
    }
    //上传新视频/音频
    @IBAction func addClick(_ sender: UIButton) {
        MPSideA_ModalType = .Choice
        let addVC = MPSideA_AddViewController()
        addVC.modalPresentationStyle = .custom
        addVC.transitioningDelegate = self
        present(addVC, animated: true)
    }
}
//MARK: - tableView
extension MPSideA_CenterViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return MPSideA_LoadDataMusic.shared.userlistMusics.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CenterTableViewCellID, for: indexPath) as! MPSideA_CenterTableViewCell
        cell.musicView = MPSideA_LoadDataMusic.shared.userlistMusics[indexPath.row]
        cell.moreBlock = {
            [weak self] (sender) in
            self?.moreAction(sender, music: MPSideA_LoadDataMusic.shared.userlistMusics[indexPath.row])
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let music = MPSideA_LoadDataMusic.shared.userlistMusics[indexPath.row].music
        //检索当前音乐状态
        guard MPSideA_MediaCenterManager.shared.getMusic()?.identifier != music.identifier else {
            //同一首，检索是否播放中
            switch MPSideA_MediaCenterManager.shared.getPlayerState() {
            case .Null://没有播放
                MPSideA_MediaCenterManager.shared.playerStart(music, actionType: .Normal)
            case .Playing://播放中
                break
            case .Pause://继续播放
                MPSideA_MediaCenterManager.shared.playerResume()
            }
            reload()
            return
        }
        //新的一首
        MPSideA_MediaCenterManager.shared.playerStart(music, actionType: .Normal)
        reload()
    }
}
//MARK: - Popover
extension MPSideA_CenterViewController: UIPopoverPresentationControllerDelegate, UIViewControllerTransitioningDelegate {
    //不指定返回样式
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    //更多操作
    private func moreAction(_ sender:UIButton, music:MPSideA_MusicViewModel) {
        //展示对应位置的popover弹窗
        let moreVC = MPSideA_MoreViewController()
        //设置moreVC的真实大小
        moreVC.preferredContentSize = .init(width: 130*width, height: 65*width)
        moreVC.modalPresentationStyle = .popover
        moreVC.renameBlock = {
            [weak self] in
            self?.renameAction(music)
        }
        moreVC.deleteBlock = {
            [weak self] in
            self?.deleteAction(music)
        }
        let popoverVC = moreVC.popoverPresentationController
        popoverVC?.delegate = self
        //设置锚点视图
        popoverVC?.sourceView = sender
        popoverVC?.backgroundColor = .init(hex: "#434343")
        //设置箭头指示方向
        popoverVC?.permittedArrowDirections = .right
        present(moreVC, animated: true)
    }
    //弹出重命名框
    private func renameAction(_ music:MPSideA_MusicViewModel) {
        MPSideA_ModalType = .Rename
        let renameVC = MPSideA_RenameViewController()
        renameVC.renameBlock = {
            [weak self] (name) in
            music.music.title = name
            MPSideA_MusicModel.save()
            //判断是否是当前播放音乐
            if music.music.identifier == MPSideA_MediaCenterManager.shared.getMusic()?.identifier {
               //同步调整
                MPSideA_MediaCenterManager.shared.setMusic(music.music)
                NotificationCenter.notificationKey.post(notificationName: .sideA_rename_music)
            }
            //更新
            self?.reload()
        }
        renameVC.transitioningDelegate = self
        renameVC.modalPresentationStyle = .custom
        present(renameVC, animated: true)
    }
    //弹出删除框
    private func deleteAction(_ music:MPSideA_MusicViewModel) {
        MPSideA_ModalType = .Delete
        let deleteVC = MPSideA_DeleteViewController()
        deleteVC.deleteBlock = {
            [weak self] in
            //判断是否是当前播放音乐
            if music.music.identifier == MPSideA_MediaCenterManager.shared.getMusic()?.identifier {
                MPSideA_MediaCenterManager.shared.setMusic(nil)
                //暂停播放
                MPSideA_MediaCenterManager.shared.playerStop()
                //发布通知让音乐展示框消失
                NotificationCenter.notificationKey.post(notificationName: .sideA_close_show)
            }
            MPSideA_MusicModel.delete(music.music)
            //更新
            self?.reload()
        }
        deleteVC.transitioningDelegate = self
        deleteVC.modalPresentationStyle = .custom
        present(deleteVC, animated: true)
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPSideA_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
