//
//  SettingViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/10.
//

import UIKit

class MPSideA_SettingViewController: MPSideA_BaseViewController {
    @IBOutlet weak var tableView: UITableView!{
        didSet{
            if #available(iOS 15.0, *) {
                tableView.sectionHeaderTopPadding = 0
            }
            tableView.rowHeight = 70*width
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(UINib(nibName: SettingTableViewCellID, bundle: nil), forCellReuseIdentifier: SettingTableViewCellID)
        }
    }
    private let SettingTableViewCellID = "MPSideA_SettingTableViewCell"
    private lazy var titles:[String] = ["About","Feedback","Share","Privacy Policy","Terms of Use","Clear Cache"]
    var cleanSide:Bool = false
    var setblock:(() -> Void)?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    @IBAction func popClick(_ sender: UIButton) {
        if setblock != nil {
            setblock!()
        }
        navigationController?.popViewController(animated: true)
    }
}
//MARK: - tableView
extension MPSideA_SettingViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SettingTableViewCellID, for: indexPath) as! MPSideA_SettingTableViewCell
        cell.title = titles[indexPath.row]
        switch indexPath.row {
        case titles.count - 1:
            cell.sizeLabel.isHidden = !cleanSide
        default:
            cell.sizeLabel.isHidden = true
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0://About
            let aboutVC = MPSideA_AboutViewController()
            navigationController?.pushViewController(aboutVC, animated: true)
        case 1://Feedback
            let alert = UIAlertController(title: "Feedback", message: "If you have any comments or suggestions, please contact us at the following e-mail address", preferredStyle: .actionSheet)
            let email = UIAlertAction(title: "marketing@lux-ad.com", style: .default) { (_) in
                //将邮箱复制到剪切板中
                UIPasteboard.general.string = "marketing@lux-ad.com"
                MP_HUD.text("Successfully copied the e-mail address to the clipboard", delay: 1.0, completion: nil)
            }
            alert.addAction(email)
            let cancel = UIAlertAction(title: "Cancel", style: .cancel)
            alert.addAction(cancel)
            present(alert, animated: true)
        case 2://Share
            //设置分享文本
            let text = App_Name
            //分享图片icon
            let image = UIImage(named: "ICON")
            //设置分享路径
            let url = URL(string: "https://musiclax.mystrikingly.com/")
            let activityItems = [text,image as Any,url as Any]
            //弹出分享框
            let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities:nil)
            present(activityViewController, animated: true, completion: nil)
            //分享结束后的回调
            activityViewController.completionWithItemsHandler = { [weak self] ( activityType, isCompleted, returnedItems, error) -> Void in
                print(isCompleted ? "Share Success":"Share Failure")
            }
        case 3:
            MP_NetWorkManager.shared.requestNetworkPermission(oberve: self) {
                [weak self] in
                let privacyVC = MPSideA_PrivacyViewController()
                self?.navigationController?.pushViewController(privacyVC, animated: true)
            }
        case 4:
            MP_NetWorkManager.shared.requestNetworkPermission(oberve: self) {
                [weak self] in
                let serviceVC = MPSideA_ServiceViewController()
                self?.navigationController?.pushViewController(serviceVC, animated: true)
            }
        default://清除缓存
            if cleanSide {
                //清除B面缓存数据
                let alertController = UIAlertController(title: "Clear Cache", message: "Clearing the cache can help free up storage space and resolve possible playback issues. Are you sure you want to do this?", preferredStyle: .alert)
                let cancel = UIAlertAction(title: "Cancel", style: .cancel)
                alertController.addAction(cancel)
                let sure = UIAlertAction(title: "Sure", style: .destructive) { [weak self] (action) in
                    MP_HUD.loading()
                    MP_CacheAndArchiverManager.shared.cleanAllCache { statu in
                        if statu {
                            //清除成功
                            MP_HUD.hideNow()
                            MP_HUD.success("Successfully", delay: 1.0, completion: nil)
                        }else {
                            //清除失败
                            MP_HUD.hideNow()
                            MP_HUD.error("Failed", delay: 1.0, completion: nil)
                        }
                        tableView.reloadData()
                    }
                }
                alertController.addAction(sure)
                present(alertController, animated: true)
            }else {
                //清除A面缓存数据
                let alertController = UIAlertController(title: "Clear Cache", message: "Clicking “Sure” will clear your uploaded media assets. Are you sure you want to do this?", preferredStyle: .alert)
                let cancel = UIAlertAction(title: "Cancel", style: .cancel)
                alertController.addAction(cancel)
                let sure = UIAlertAction(title: "Sure", style: .destructive) { [weak self] (action) in
                    MP_HUD.loading()
                    MPSideA_LoadDataMusic.shared.userlistMusics.forEach { music 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)
                    }
                    MP_HUD.hideNow()
                    MP_HUD.success("Successfully", delay: 1.0, completion: nil)
                    tableView.reloadData()
                }
                alertController.addAction(sure)
                present(alertController, animated: true)
            }
        }
    }
}
