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
        const result = await window.electronAPI.runNodejsScript('adb-connect', ip, '5555')
    
        if(result.stdout == 'success') {
            hintView.setContent('设备添加成功')
            hintView.show()

            await this.addDevice(ip);
          
            return;
        }
        alertView.show()
        alertView.setContent('无法检测到连接设备')
    }

    async addDevice(ip) {   
        // 数组中是字符串，直接 push IP 字符串
        this.deviceArr.push(ip)
        await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: this.deviceArr}))

        this.setDeviceList(this.deviceArr);
    }

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

        comfirmView.onConfirm = async () => {
            comfirmView.hide()
            
            // 从数组中移除指定 IP（deviceIp 是数组中的每个字符串元素）
            this.deviceArr = this.deviceArr.filter(deviceIp => deviceIp !== ip)

            // 更新 JSON 文件
            await window.electronAPI.runNodejsScript('json-parser', 'update', 'device_list.json', JSON.stringify({devices: this.deviceArr}))
          
            this.setDeviceList(this.deviceArr)
        }
        comfirmView.onCancel = () => {
            comfirmView.hide()
        }
    }
}

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