//
//  MPPositive_ChoosePlayListViewController.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/6/24.
//

import UIKit
///选择歌单
class MPPositive_ChoosePlayListViewController: UIViewController, UIViewControllerTransitioningDelegate {
    //小角标图片
    private lazy var indictorImageView:UIImageView = .init(image: .init(named: "Player_Indictor'logo"))
    //tableView
    private lazy var tableView:UITableView = {
        let tableView = UITableView(frame: .init(x: 0, y: 0, width: screen_Width, height: screen_Height), style: .plain)
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableView.automaticDimension
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(MPPositive_ChooseNewPlayListTableViewCell.self, forCellReuseIdentifier: MPPositive_ChooseNewPlayListTableViewCellID)
        tableView.register(MPPositive_LibraryTableViewCell.self, forCellReuseIdentifier: MPPositive_LibraryTableViewCellID)
        tableView.contentInset = .init(top: 0, left: 0, bottom: 70*width, right: 0)
        return tableView
    }()
    private let MPPositive_LibraryTableViewCellID = "MPPositive_LibraryTableViewCell"
    private let MPPositive_ChooseNewPlayListTableViewCellID = "MPPositive_ChooseNewPlayListTableViewCell"
    private var song:MPPositive_SongItemModel!
    var disMissBlock:(() -> Void)?
    init(_ song:MPPositive_SongItemModel) {
        super.init(nibName: nil, bundle: nil)
        self.song = song
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .init(hex: "#282A2C")
        view.layer.masksToBounds = true
        view.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
        view.layer.cornerRadius = 18*width
        configure()
    }
    private func configure() {
        view.addSubview(indictorImageView)
        indictorImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(29*width)
            make.height.equalTo(4*width)
            make.top.equalToSuperview().offset(8*width)
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(18*width)
            make.left.right.bottom.equalToSuperview()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //注册监听
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(reloadAction(_ :)), notificationName: .create_custom_playlist)
        reload()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    //收到通知，刷新页面
    @objc private func reloadAction(_ sender:Notification) {
        reload()
    }
    //刷新页面
    private func reload(){
        MPPositive_LoadCoreModel.shared.reloadCustomPlayLists {
            [weak self] in
            guard let self = self else {return}
            tableView.reloadData()
        }
    }
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    //新增歌单
    @objc private func newAction() {
        //弹出新增自定义框
        MPPositive_ModalType = .NewList
        let listVC = MPSideA_RenameViewController()
        listVC.titleText = "Name Your PlayList"
        listVC.renameBlock = {
            [weak self] text in
            //新建一个自定歌单列表
            let list = MPPositive_CustomPlayListModel.create()
            list.playListId = Date().timeZone().toString(.custom("YYYY/MM/dd/HH:mm:ss"))
            list.title = text
            list.createTime = Date().timeZone()
            list.addToRelationshipToCustomVideos([])
            MPPositive_CustomPlayListModel.save()
            //成功新建歌单列表
            print("成功新建\(text)歌单")
            //发布通知
            NotificationCenter.notificationKey.post(notificationName: .create_custom_playlist)
        }
        listVC.transitioningDelegate = self
        listVC.modalPresentationStyle = .custom
        present(listVC, animated: true)
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
//MARK: - tableView
extension MPPositive_ChoosePlayListViewController:UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return MPPositive_LoadCoreModel.shared.playLists.count + 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.row {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_ChooseNewPlayListTableViewCellID, for: indexPath) as! MPPositive_ChooseNewPlayListTableViewCell
            cell.newBlock = {
                [weak self] in
                self?.newAction()
            }
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_LibraryTableViewCellID, for: indexPath) as! MPPositive_LibraryTableViewCell
            cell.playList = MPPositive_LoadCoreModel.shared.playLists[indexPath.row-1]
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            break
        default:
            //选择了一个歌单
            let playList = MPPositive_LoadCoreModel.shared.playLists[indexPath.row-1].playList
            let videos = playList.videosArray
            //判断videos中是否存在当前歌曲
            if videos.first(where: {$0.videoId == song.videoId}) != nil {
                //不为空的情况下，说明有选中歌单有这首歌，弹出HUD
                MP_HUD.onlytext("The song already exists in the current playlist", delay: 1.5, completion: nil)
            }else{
                //为空，将歌曲存入选中歌单
                let video = MPPositive_CustomVideoModel.create()
                video.coverImageURL = .init(string: song.reviewUrls?.last ?? "")
                video.title = song.title
                video.subtitle = song.shortBylineText
                video.videoId = song.videoId
                video.lyricsID = song.lyricsID
                video.relatedID = song.relatedID
                video.addTime = Date().timeZone()
                video.playList = playList
                MPPositive_CustomVideoModel.save()
                MP_HUD.onlytext("Successfully added to the playlist", delay: 1.5) {
                    [weak self] in
                    self?.dismiss(animated: true, completion: {
                        [weak self] in
                        if let block = self?.disMissBlock {
                            block()
                        }
                    })
                }
            }
        }
    }
}
 
