//
//  PQEditSdataModel.swift
//  PQSpeed
//
//  Created by ak on 2020/12/16.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import ObjectMapper
import RealmSwift
import UIKit
import BFCommonKit

public class PQEditSdataModel: PQEditBaseModel {
    @objc dynamic public var systemParam: PQEditSystemParamModel?
    @objc dynamic public var videoMetaData: PQEditVideoMetaDataModel?
    public var sections: List<PQEditSectionModel> = List()

    required convenience public init?(map _: Map) {
        self.init()
    }

    required public  init() {
        super.init()
        systemParam = PQEditSystemParamModel()
        videoMetaData = PQEditVideoMetaDataModel()
    }

    public  override func mapping(map: Map) {
        systemParam <- map["systemParam"]
        videoMetaData <- map["videoMetaData"]
        sections <- (map["sections"], PQListTransform<PQEditSectionModel>())
    }

   public  func deleteBGM() {
        var selectBGMIndex: Int = -1
        for (i, section) in sections.enumerated() {
            if section.sectionType == "global" {
                selectBGMIndex = i
            }
        }
        if selectBGMIndex != -1 {
            BFLog(message: "DELETE BGM INDEX\(selectBGMIndex)")
            sections.remove(at: selectBGMIndex)
        }
    }

    // 添加背景音乐
   public  func addBGM(audioMix: PQVoiceModel) {
        // 1,如果已经选择过就先删除一次
        deleteBGM()

        // 所有段落的时长
        var sectionDuration: Float64 = 0
        for section in sections {
            if section.sectionType == "normal" {
                sectionDuration = sectionDuration + section.sectionDuration
            }
        }

        // 拼接数据
        let bgmSection = PQEditSectionModel()
        bgmSection.sectionType = "global"
        bgmSection.sectionIndex = 0
        bgmSection.projectTimelineIn = 0
        bgmSection.projectTimelineOut = sectionDuration

        bgmSection.sectionDuration = Float64(audioMix.duration ?? "0")!
        let audioTrackModel = PQEditAudioTrackModel()
        let audioTrackMaterial = PQEditAudioTrackMaterialModel()
        audioTrackMaterial.id = 0
        audioTrackMaterial.type = "voice"
        audioTrackMaterial.voiceType = VOICETYPT.BGM.rawValue
        // 背景音乐的时长
        audioTrackMaterial.duration = Float64(audioMix.duration ?? "0")!
        audioTrackMaterial.timelineIn = 0
        // 所有段落的总时长
        audioTrackMaterial.timelineOut = sectionDuration
        // 裁剪位置
        audioTrackMaterial.model_in = audioMix.startTime
        audioTrackMaterial.out = (audioMix.endTime == 0 ? Float64(audioMix.duration ?? "0") : audioMix.endTime)!

        audioTrackMaterial.volumeGain = Float64(audioMix.volume)

        let materialDurationFit = PQEditmaterialDurationFitModel()
        materialDurationFit.fitType = "loop"
        materialDurationFit.loopValue = 1

        audioTrackMaterial.materialDurationFit = materialDurationFit

        let bgmInfo = PQEditBgmInfoModel()
        bgmInfo.musicId = audioMix.musicId ?? ""
        bgmInfo.originType = audioMix.originType
        bgmInfo.selectVoiceType = audioMix.selectVoiceType
        bgmInfo.rhythmMusicSpeed = audioMix.speed
        audioTrackMaterial.bgmInfo = bgmInfo
        audioTrackModel.audioTrackMaterials.append(audioTrackMaterial)
        bgmSection.sectionTimeline?.audioTrack = audioTrackModel

        sections.append(bgmSection)
    }

    // 取背景音乐的 session
   public  func getBGMSession() -> PQEditSectionModel? {
        var BGMSession: PQEditSectionModel?
        if sections.count > 0 {
            for section in sections {
                if section.sectionType == "global" {
                    BGMSession = section
                }
            }
        }

        return BGMSession
    }

    // 取有效素材的段落剔除 global BGM 的 session  , type is normal
   public  func getVoisonSessions() -> List<PQEditSectionModel> {
        let voisonArray = List<PQEditSectionModel>.init()
        for section in sections {
            if section.sectionType == "normal" {
                voisonArray.append(section)
            } else { BFLog(message: "有音频bgm session") }
        }
        BFLog(message: "有效视觉段落数 \(voisonArray.count)")
        return voisonArray
    }

    ///
   public  func deleteDisableSaveMaterials() {}

    // 删除无效的素材
    /// - Parameter isSaveDraft: 只能在保存项目API 调用前使用COPY 的 sdata 设TRUE ，恢复项目时设置 false
   public  func deleteDisableMaterials(isSaveDraft: Bool = false) {
        for section in sections {
            // 视觉素材sr
            let visionTrackMaterialsTemp = List<PQEditVisionTrackMaterialsModel>.init()
            for visionTrackMaterialsModel in section.sectionTimeline?.visionTrack?.visionTrackMaterials ?? List<PQEditVisionTrackMaterialsModel>.init() {
                if visionTrackMaterialsModel.type == "subtitle" {
                    visionTrackMaterialsTemp.append(visionTrackMaterialsModel)

                } else if (isSaveDraft && visionTrackMaterialsModel.materialUrl.count > 0) || (!isSaveDraft && (visionTrackMaterialsModel.locationPath.count > 0 || visionTrackMaterialsModel.materialUrl.count > 0)) {
                    visionTrackMaterialsTemp.append(visionTrackMaterialsModel)

                } else { BFLog(message: "visionTrackMaterialsModel 这个无效") }
            }
            section.sectionTimeline?.visionTrack?.visionTrackMaterials = visionTrackMaterialsTemp

            // 音频素材
            let audioTrackMaterialModelTemp = List<PQEditAudioTrackMaterialModel>.init()
            for audioTrackMaterialModel in section.sectionTimeline?.audioTrack?.audioTrackMaterials ?? List<PQEditAudioTrackMaterialModel>.init() {
                if audioTrackMaterialModel.voiceType == VOICETYPT.PRODUCE.rawValue || audioTrackMaterialModel.voiceType == VOICETYPT.BGM.rawValue || (isSaveDraft && audioTrackMaterialModel.materialUrl.count > 0) || (!isSaveDraft && (audioTrackMaterialModel.locationPath.count > 0 || audioTrackMaterialModel.materialUrl.count > 0)) {
                    audioTrackMaterialModelTemp.append(audioTrackMaterialModel)

                } else { BFLog(message: "audioTrackMaterialModel 这个无效") }
            }
            section.sectionTimeline?.audioTrack?.audioTrackMaterials = audioTrackMaterialModelTemp
        }
    }
}
