import comfirmView from '../public/comfirm-view/comfirm-view.js'
import hintView from '../public/hint-view/hint-view.js'
import alertView from '../public/alert-view/alert-view.js'

// 设备管理类，所有方法都可以通过 this. 访问属性
class DeviceClass {
    constructor(setDeviceList) {
        this.deviceArr = []
        this.setDeviceList = setDeviceList
    }

    async init() {
 
        let readResult = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json')

        if (readResult.stdout === '') {
            await window.electronAPI.runNodejsScript('json-parser', 'create', 'device_list.json', JSON.stringify({devices: []}))
            if (this.setDeviceList) {
                this.setDeviceList([])
            }
        } 
        else
        {
            const jsonData = JSON.parse(readResult.stdout)
            this.deviceArr = jsonData.data.devices
            if (this.setDeviceList) {
                this.setDeviceList(this.deviceArr)   
            }
        }
    }

    async handleRefresh(e, self) {
        self.startAnimation()

        this.scanDevice(() => {
            self.stopAnimation()
        });
    }

    async scanDevice(callback)
    {
        for (let i = 0; i <= 3; i++) {
            for (let j = 0; j <= 255; j++) 
            {
                const ip = `192.168.${i}.${j}`
                const result = await window.electronAPI.runNodejsScript('adb-connect', ip, '5555')
                if (result.stdout == 'success') {
                    await this.addDevice(ip)
                }
            }  
        }
        callback();
    }

    async handleAdd() {
  
        const ip = document.querySelector('.ip-input input').value
        hintView.setContent(ip)
        hintView.show()
        const result = await window.electronAPI.runNodejsScript('adb-connect', ip, '5555')
    
        if(result.stdout == 'success') {
            const newDevice = await this.addDevice(ip)
            if (newDevice && this.setDeviceList) { 
                this.setDeviceList(prev => [...prev, newDevice])

                hintView.setContent('设备添加成功')
                hintView.show()
            }
            return
        }

        alertView.show()
        alertView.setContent('无法检测到连接设备')
    }

    async addDevice(ip) {
        const readResult = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json')
        
        let jsonData
        if (readResult.stdout === '') {
            await window.electronAPI.runNodejsScript('json-parser', 'create', 'device_list.json', JSON.stringify({devices: []}))
            jsonData = {devices: []}
        } else {
            const parsed = JSON.parse(readResult.stdout)
            jsonData = parsed.data || {devices: []}
        }
        
        // 数组中是字符串，直接 push IP 字符串
        jsonData.devices.push(ip)
        await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: jsonData.devices}))

        // 更新 this.deviceArr
        this.deviceArr = jsonData.devices
        this.setDeviceList(jsonData.devices);
        return ip
    }

    async removeDevice(ip) {
        
        comfirmView.show()
        comfirmView.setContent('确定要删除设备吗？')
        comfirmView.onConfirm = async () => {
            comfirmView.hide()

            const readResult = await window.electronAPI.runNodejsScript('json-parser', 'read', 'device_list.json')
        
            if (readResult.stdout === '') {
                return
            }
            
            const parsed = JSON.parse(readResult.stdout)
            const jsonData = parsed.data || {devices: []}
            
            // 过滤掉要删除的设备（数组中是字符串，直接比较）
            const filteredDevices = jsonData.devices.filter(deviceIp => deviceIp !== ip)
            
            // 更新 JSON 文件
            await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: filteredDevices}))
            
            // 更新 this.deviceArr
            this.deviceArr = filteredDevices
            
            // 更新 deviceArrRef
            if (this.deviceArrRef) {
                this.deviceArrRef.current = filteredDevices
            }
            
            // 更新 React state
            if (this.setDeviceList) {
                this.setDeviceList(filteredDevices)
            }
        }
        comfirmView.onCancel = () => {
            comfirmView.hide()
        }
    }
}

// 导出类，由组件创建实例并管理生命周期
export { DeviceClass}
